when I try to create the file in my server space, it seems corrupted
Have you compared the input file to the output file (byte by byte) to see exactly what the differences are?
Where do you read/handle binary/non-text data? Your posted code appears to only handle text.
NormR1
Posting Expert
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
You are reading the incoming data as text/characters vs as binary bytes.
clientData += line + '\n';
What does this line do?
NormR1
Posting Expert
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
Files made of binary data like images don't contain "lines" with line-end characters.
They contain bytes with any of 256 different values.
NormR1
Posting Expert
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
Get a HexEditor and look at the contents of different types of files.
NormR1
Posting Expert
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
You may still be creating problems by trying to read binary data as if it is character. That will read 1 byte per character from the input stream, but convert to Unicode 2-byte chars to store in a char array, with results that may be unexpected for random binary input.
To read a binary file you can read it verbatim from the input stream (not a Reader) in nice chunks with
read(byte[] b) - Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer.
By way of illustration, here a little bit of code that does the opposite of your case - ie copies an arbitrary binary file from a local file to a remote client - but it illustrates the ideas well
public void send(InputStream file, String mimeType, Socket clientSocket) {
// send a file that has an input stream already opened
try {
// Acquire an output stream
DataOutputStream outbound = new DataOutputStream(clientSocket
.getOutputStream());
// Send the response header and content
outbound.writeBytes("HTTP/1.0 200 OK\r\n");
outbound.writeBytes("Content-type: " + mimeType + "\r\n");
outbound.writeBytes("Content-Length: " + file.available() + "\r\n");
outbound.writeBytes("\r\n");
byte[] data = new byte[4096];
int count;
while ((count = file.read(data)) != -1) {
outbound.write(data, 0, count);
}
file.close();
outbound.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
JamesCherrill
Posting Genius
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073