Springboot下载功能,附件超过8K不能显示下载弹窗,页面乱码问题

Posted wanbao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot下载功能,附件超过8K不能显示下载弹窗,页面乱码问题相关的知识,希望对你有一定的参考价值。

Springboot项目中遇到一个文件下载问题,当文件大小超过8K时,不会出现弹出窗,而是直接在页面显示乱码。

有问题的源码如下:

@RequestMapping(value = "/exportFile")
public void exportFile(HttpServletRequest request, HttpServletResponse response, String fileName) {
    String filePath = ReflectUtil.class.getClassLoader().getResource("").getPath();
    File exportfile = new File(filePath + "/export/" + fileName);
    try (FileInputStream is = new FileInputStream(exportfile ); OutputStream out = response.getOutputStream();) {
        if (is != null) {
            int b = 0;
            byte[] buffer = new byte[4096];
            while (b != -1) {
                b = is.read(buffer);
                if (b != -1) {
                    out.write(buffer, 0, b);
                }
            }
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + "exportFile.xls");
            response.flushBuffer();
            out.flush();
        }
    } catch (IOException e) {
        log.error("error is {}", e);
    }
} 

 

解决方案:将上面蓝色标识的二行放到方法最上面,问题解决。

@RequestMapping(value = "/exportFile")
public void exportFile(HttpServletRequest request, HttpServletResponse response, String fileName) {
    response.setContentType("application/octet-stream");
    response.setHeader("Content-disposition", "attachment;filename=" + "exportFile.xls");
    String filePath = ReflectUtil.class.getClassLoader().getResource("").getPath();
    File exportfile = new File(filePath + "/export/" + fileName);
    try (FileInputStream is = new FileInputStream(exportfile ); OutputStream out = response.getOutputStream();) {
        if (is != null) {
            int b = 0;
            byte[] buffer = new byte[4096];
            while (b != -1) {
                b = is.read(buffer);
                if (b != -1) {
                    out.write(buffer, 0, b);
                }
            }
            response.flushBuffer();
            out.flush();
        }
    } catch (IOException e) {
        log.error("error is {}", e);
    }
} 

 

以上是关于Springboot下载功能,附件超过8K不能显示下载弹窗,页面乱码问题的主要内容,如果未能解决你的问题,请参考以下文章

怎么在论坛不能上传附件了```

求C# MVC4 做的上传附件下载附件的功能 附件路径存在数据库中 附件存在项目下的uploading文件中 求源码

帝国CMS采集功能不能直接保存其他格式附件吗?

我想用手机发送超过100kb的邮件,显示您必须连接到无线局域网才能发送此附件,可是我明明链接

DISCUZ2.5上传大附件完毕之后,不显示。

求如何突破论坛积分限制下载附件?