Search code examples
fileservletshttprequestfileinputstream

how to remove request header from HttpInputStream


I need help with a servlet.

I need to read a inputStream in one request and write a tiff file. The inputStream come with request header and i dont know how remove that bytes and write only the file.

See initial bytes from the writen file.

-qF3PFkB8oQ-OnPe9HVzkqFtLeOnz7S5Be
Content-Disposition: form-data; name=""; filename=""
Content-Type: application/octet-stream; charset=ISO-8859-1
Content-Transfer-Encoding: binary

I want to remove that and write only bytes from the tiff file. PS: sender of file its not me.


Solution

  • Apache commons solve 90% of your problems... only need know what keywords use in search :)
    "parse multipart request" and google say: http://www.oreillynet.com/onjava/blog/2006/06/parsing_formdata_multiparts.html

    int boundaryIndex = contentType.indexOf("boundary=");
    byte[] boundary = (contentType.substring(boundaryIndex + 9)).getBytes();
    
    ByteArrayInputStream input = new ByteArrayInputStream(buffer.getBytes());
    MultipartStream multipartStream =  new MultipartStream(input, boundary);
    
    boolean nextPart = multipartStream.skipPreamble();
    while(nextPart) {
      String headers = multipartStream.readHeaders();
      System.out.println("Headers: " + headers);
      ByteArrayOutputStream data = new ByteArrayOutputStream();
      multipartStream.readBodyData(data);
      System.out.println(new String(data.toByteArray());
    
      nextPart = multipartStream.readBoundary();
    }