springmvc -》文件下载

前言:

  1. 在项目webapp目录下创建files文件夹,并在springmvc文件夹中配置静态资源
<mvc:resources location="/files/" mapping="/files/**"></mvc:resources>

         2.files目录下添加a.txt和test.zip

             

  3.创建download.jsp

<a href="files/a.txt">下载</a>

启动项目:

4.修改

<a href="files/test.zip">下载</a>

启动项目:

根据两者对比,总结:访问资源时响应头如果没有设置Content-Disposition,浏览器默认按照inline值进行处理,也就是,能显示就显示,不能显示就下载

正文:

  1. 导入依赖
<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.2</version>
    </dependency>

2.修改超链接,并在配置文件中放行静态资源files,前面已经写过。

<a href="download?filename=test.zip">下载</a>

3.控制器开发

@RequestMapping("download")
    public void download(String filename,HttpServletRequest req,HttpServletResponse resp) throws IOException{
        
        //设置响应流文件进行下载
        resp.setHeader("Content-Disposition","attachment;filename="+filename);
        ServletOutputStream sos = resp.getOutputStream();
        File file = new File(req.getServletContext().getRealPath("files"), filename);//这个路径为磁盘开始
        byte[] bytes = FileUtils.readFileToByteArray(file);
        sos.write(bytes);
        sos.flush();
        sos.close();
    }

这样,任意格式都会以文件的形式下载了》》》》

总结:修改响应头中Context-Disposition="attachment;filename=文件名", attachment下载以附件的形式下载。

猜你喜欢

转载自www.cnblogs.com/dylq/p/10578151.html
今日推荐