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

时间:2012-12-03 06:14:22

标签: 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,text,doc文件....但问题出在图像文件中......

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

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

3 个答案:

答案 0 :(得分:6)

最后我设法做到了这一点...... 问题在于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());
        }
     }

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

感谢您的回复:)

答案 1 :(得分:1)

检查以下链接,

JSP download - application/octet-stream

可以帮助您解决问题。

答案 2 :(得分:1)

对于图像你应该使用setContentType(image / jpg)。你可以查看这个链接的mime类型

http://webdesign.about.com/od/multimedia/a/mime-types-by-content-type.htm

相关问题