Sashimi
Sashimi

Reputation: 113

receiving files via HTTP post in java: Files corrupted

I've just wrote an HTTP server that receive POST request via HTTP. In particular it receives requests as multipart form data:

POST / HTTP/1.1
Host: 192.168.7.4:5000
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0
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
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------197987737412371961922053527775
Content-Length: 4306786


-----------------------------197987737412371961922053527775
Content-Disposition: form-data; name="filename"

poison.mp3
-----------------------------197987737412371961922053527775
Content-Disposition: form-data; name="prova"

provaV
-----------------------------197987737412371961922053527775
Content-Disposition: form-data; name="datafile"; filename="01-Poison.mp3"
Content-Type: audio/mpeg

file......

After the Header every input is encripted in the form:

-----------------------------197987737412371961922053527775 Conten_disposition ...\r\n\r\n "input content"

The last one contains the file in binary form.

This is my Server that first grabs all informations contained in the header then try to rebuild the file. If i send a request from my local machines it works fine, but if I try to send a file from a remote client it corrupts the file. I'm using a simple InputStream directly opened from the socket.

This is the method that tries to created the sent file:

private void payloadFileCreation(InputStream in,boolean t1, FileOutputStream fos, long filesize ) throws IOException{

    int dyn_data_index=0;
    int chunk=2048;
    byte[] dyn_data = new byte[chunk];
    int av = in.available();
    while (filesize>chunk){
           in.read(dyn_data,0,chunk);
           fos.write(dyn_data,0,chunk);
       fos.flush();
       filesize -= chunk;

    }
    in.read(dyn_data,0,(int) filesize );
    fos.write(dyn_data,0, (int) filesize);
    fos.flush();
    fos.close();

    }

any ideas? Thanks

Upvotes: 1

Views: 2215

Answers (1)

Sergey Aslanov
Sergey Aslanov

Reputation: 2415

You can use Apache Commons FileUpload library to parse multipart form requests.

Upvotes: 3

Related Questions