在jsp中下载任何文件格式的内容类型应该是什么? [英] What should be the content type to download any file format in jsp?

查看:120
本文介绍了在jsp中下载任何文件格式的内容类型应该是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make a provision to download all file types...Is there any way to download any file format in 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文件....但是问题在于图像文件...

If I specify setContentType as APPLICATION/OCTET-STREAM, pdf, text, doc files are getting downloaded.... But the problem is with image files...

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

What is problem with image files? I want to download all image file types...

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

I searched similar questions but could not find proper answer... Thanks...

推荐答案

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

Finally I somehow managed to do this... The problem is with JSP's "Out.write", which is not capable of writing byte stream...

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

I replaced jsp file with servlet...

代码段为:

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

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

Now I can download all types of files....

感谢您的回复:)

这篇关于在jsp中下载任何文件格式的内容类型应该是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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