java - 在jsp中下载任何文件格式的内容类型应该是什么?

标签 java jsp

我想规定下载所有文件类型...有没有办法在 jsp 中下载任何文件格式...

我的代码片段:

    String filename = (String) request.getAttribute("fileName");        
    response.setContentType("APPLICATION/OCTET-STREAM");
    String disHeader = "Attachment";
    response.setHeader("Content-Disposition", disHeader);

    // transfer the file byte-by-byte to the response object
    File fileToDownload = new File(filename);
    response.setContentLength((int) fileToDownload.length());
    FileInputStream fileInputStream = new FileInputStream(fileToDownload);
    int i = 0;
    while ((i = fileInputStream.read()) != -1) {
        out.write(i);
    }
    fileInputStream.close();

如果我将 setContentType 指定为 APPLICATION/OCTET-STREAM,将下载 pdf、文本、doc 文件....但问题在于图像文件...

图像文件有什么问题?我想下载所有图像文件类型...

我搜索了类似的问题,但找不到合适的答案... 谢谢...

最佳答案

最后我以某种方式设法做到了...... 问题出在 JSP 的“Out.write”,它不能写入字节流...

我用 servlet 替换了 jsp 文件...

代码片段是:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        String filename = (String) request.getAttribute("fileName");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment;filename="+filename);

        File file = new File(filename);
        FileInputStream fileIn = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();

        byte[] outputByte = new byte[(int)file.length()];
        //copy binary contect to output stream
        while(fileIn.read(outputByte, 0, (int)file.length()) != -1)
        {
        out.write(outputByte, 0, (int)file.length());
        }
     }

现在我可以下载所有类型的文件....

感谢您的回复:)

关于java - 在jsp中下载任何文件格式的内容类型应该是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13678094/

相关文章:

java - TightVNC Java 查看器连接

Java忽略字符串

java - 建议在移动设备上使用对象池 : evil on desktop,。这怎么可能?

jquery - 将数据传递到 Bootstrap 模式

java - 如何在jsp页面上显示通过ajax查询传递的日语字符

java - 如何从 ajax post 重定向到 servlet 到 jsp?

java - 使用 apache VFS 创建虚拟文件系统

java - 更新 Java 类/play2 中的 View 参数

java - 使用 Eclipse 和 Tomcat (Servlet 3.0) 在 web-fragment 中热部署 JSP

java - 无法通过 JSP 生成根认证