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

Java 在jsp中下载任何文件格式的内容类型应该是什么?,java,jsp,Java,Jsp,我想规定下载所有文件类型…有没有办法下载jsp中的任何文件格式 我的代码片段: String filename = (String) request.getAttribute("fileName"); response.setContentType("APPLICATION/OCTET-STREAM"); String disHeader = "Attachment"; response.setHeader("Content-Disposition

我想规定下载所有文件类型…有没有办法下载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、文本、文档文件。。。。但问题是图像文件

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

我搜索了类似的问题,但找不到正确的答案。。。
谢谢…

查看以下链接


可能会帮助您解决此问题

对于图像,您应该使用setContentType(image/jpg)。您可以签出mime类型的此链接


最后我还是设法做到了。。。 问题是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());
        }
     }
现在我可以下载所有类型的文件


感谢您的回复:)

Try,
response.setHeader(“内容处置”、“附件;文件名=“+filename”)有,而且具体一点是值得的。@AVD:我试过了……它没有帮助:(我在开始时发现文件附加了一些额外的行……我在比较原始文本文件和下载的文本文件时发现了这一点。。。