Pergunta

Need a servlet to download a file from path like /home/Bureau.. in jee gwt I used this but isn't work and I went to download all file's type image

 String filePath = request.getParameter("file");
    String fileName = "test";
 FileInputStream fileToDownload = new FileInputStream(filePath);
    //   ServletOutputStream output = response.getOutputStream();
    response.setHeader("Content-Type", "image/png");
      //response.setContentType("image/png");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".png\"");
 //                        response.setContentLength(fileToDownload.available());

    int readBytes = 0;
    byte[] buffer = new byte[10000];
    while ((readBytes = fileToDownload.read(buffer, 0, 10000)) != -1) {
        //output.write(readBytes);
        response.getOutputStream().write(readBytes);
    }

    response.getOutputStream().close();
    fileToDownload.close();
    fileToDownload.close();
Foi útil?

Solução

The problem is at below line where you are writing no of bytes not actual bytes. Here readBytes represents no of bytes read at a time where as buffer contains actual bytes that is read.

response.getOutputStream().write(readBytes);

Try

OutputStream outputStream = response.getOutputStream();

while ((readBytes = fileToDownload.read(buffer)) != -1) {
    outputStream.write(buffer,0,readBytes);
}

outputStream.close(); 

I suggest you to call response.getOutputStream() single time.

Your code will give you IndexOutOfBoundsException if the size of the file is less than 10000 bytes because of below line

 fileToDownload.read(buffer, 0, 10000)

Change it to

fileToDownload.read(buffer)

Use ServletContext to get file path.

ServletContext context = getServletContext();

For more info have a look at below posts:

Writing image to servlet response with best performance.

How do I return an image from a servlet using ImageIO?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top