need a servlet to download a file from path like /home/Bureau

房东的猫 提交于 2019-12-12 04:40:00

问题


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();

回答1:


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?



来源:https://stackoverflow.com/questions/23110475/need-a-servlet-to-download-a-file-from-path-like-home-bureau

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!