需要servlet从/ home / Bureau等路径下载文件 [英] need a servlet to download a file from path like /home/Bureau

查看:127
本文介绍了需要servlet从/ home / Bureau等路径下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要一个servlet从路径下载文件,如/ home / Bureau ..在jee gwt
我使用这个但不工作
,我去下载所有文件的类型图像

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


推荐答案

问题出在下面你写的不是的字节不是实际的字节。这里 readBytes 表示一次读取的字节数,因为 buffer 包含读取的实际字节。

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






我建议您致电 response.getOutputStream()单次。

您的代码将给您 IndexOutOfBoundsException 如果文件的大小小于10000字节,因为

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)

将其更改为

fileToDownload.read(buffer)






使用 ServletContext 获取文件路径。

ServletContext context = getServletContext();

有关更多信息,请查看以下帖子:

For more info have a look at below posts:

将图像写入servlet响应性能最好

如何使用ImageIO从servlet返回图像?

这篇关于需要servlet从/ home / Bureau等路径下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆