【问题标题】:What should be the content type to download any file format in jsp?在jsp中下载任何文件格式的内容类型应该是什么?
【发布时间】:2012-11-20 14:44:47
【问题描述】:

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

我的代码sn-p:

    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 文件……但问题在于图像文件……

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

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

【问题讨论】:

  • 试试,response.setHeader("Content-Disposition", "attachment; filename=" + filename);
  • a whole smattering of image mime types,具体一点是值得的。
  • @AVD: 我试过了...它没有帮助:(
  • 我发现文件开头附加了一些额外的行...当我将原始文本文件与下载的文本文件进行比较时,我发现了...

标签: java jsp


【解决方案1】:

检查以下链接,

JSP download - application/octet-stream

可能会帮助您解决问题。

【讨论】:

    【解决方案2】:

    对于图像,您应该使用 setContentType(image/jpg)。您可以查看此链接以了解 mime 类型

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

    【讨论】:

      【解决方案3】:

      最后我设法做到了... 问题在于 JSP 的“Out.write”,它无法写入字节流...

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

      代码sn-p是:

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

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

      感谢您的回复:)

      【讨论】:

        猜你喜欢
        • 2013-07-29
        • 2010-09-16
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-15
        • 2013-03-15
        • 1970-01-01
        相关资源
        最近更新 更多