Search code examples
javapostinputstreamfilenames

Java request getInputStream return empty stream


I've got a problem with getInputStream from doPost request and setting filename before. It's giving me a file with right filename but empty file 0kB. If I'll comment setting fileName than I'll get not empty file.

My process: From android apps I'm archiving PDF file to upload server like http POST. At server doPost is like below method.

How to set filename and get not empty file?

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
    String fileName = null;
    //Get all the parts from request and write it to the file on server
    //getFileName return filename
    for (Part part : request.getParts()) {
        fileName = getFileName(part);
    }
    File saveFile = new File(SAVE_DIR + fileName);

    // opens input stream of the request for reading data
    InputStream inputStream = request.getInputStream();

    // opens an output stream for writing file
    FileOutputStream outputStream = new FileOutputStream(saveFile);

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);           
    }
    outputStream.close();
    inputStream.close();

    // sends response to client
    response.getWriter().print("UPLOAD DONE");

}

Edit:

private String getFileName(Part part) {
    String contentDisp = part.getHeader("content-disposition");
    System.out.println("content-disposition header= " + contentDisp);
    String[] tokens = contentDisp.split(";");
    for (String token : tokens) {
        if (token.trim().startsWith("filename")) {
            return token.substring(token.indexOf("=") + 2, token.length() - 1);
        }
    }
    return "";
}

Solution:

//Get the right Part
 final Part filePart = request.getPart("uploadedfile");
 //Writes file to location 
 filePart.write(filePart.getSubmittedFileName());

Solution

  • Part offers a getInputStream() method, so you should use that instead of request.getInputStream(); when you're dealing with parts.

    However...

    Part.write() is a convenience method to write this uploaded item to disk, so you can just use part.write(SAVE_DIR + part.getSubmittedFileName()); and it's all handled for you (note that getSubmittedFileName() is available only for Servlet 3.1).