Hi all,
I am writing a server in Java and I have an issue which I've been working on for days now and I can't seem to find a solution. I want to upload files to the server using an HTML form. I can read the whole POST request and the data that it contains but when I try to create the file in my server space, it seems corrupted. Here is the upload request:
POST /uploadprofilepicture HTTP/1.1
Host: www.gravyty.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://www.gravyty.com/UserHome.html
Content-Type: multipart/form-data; boundary=---------------------------105852418210285
Content-Length: 812
-----------------------------105852418210285
Content-Disposition: form-data; name="uploadfile"; filename="bday.gif"
Content-Type: image/gif
GIF89a
-----------------------------105852418210285--
and here's the way I read that request:
BufferedReader is = new BufferedReader( new InputStreamReader( s.getInputStream() ) );
String clientData = "", method = "", boundary = "", line;
int lineCount = 0;
while ( (line = is.readLine()) != null ) {
if ( line.toLowerCase().startsWith( "get" ) )
method = "g";
else if ( line.toLowerCase().startsWith( "post" ) )
method = "p";
if ( line.length() <= 0 && method.equals( "g" ) )
break;
else if ( method.equals( "p" ) ) {
if ( line.contains( "boundary=" ) ) {
boundary = line.substring( line.indexOf( "boundary=" ) + 9, line.length() );
}
else if ( !boundary.equals( "" ) && line.equals( "--" + boundary + "--" ) ) {
clientData += line + '\n'; // separate each new line.
break;
}
}
clientData += line + '\n';
lineCount++;
}
and here's how I create the file:
try {
FileOutputStream fos = new FileOutputStream( "Resources/" + name );
fos.write(data.getBytes());
fos.close();
// data is the string of symbols from the request
}
Any ideas? I have tried using JFileUpload but with no luck and I can upload .txt files.