Spring MVC 实现文件下载的方式

文件下载有两种方式

1.jsp页面直接使用超链接访问资源位置

页面:

<%@page pageEncoding="utf-8" %>
<html>
    <p><a href="image/wendang001.docx">word文档下载</a></p>
    <p><a href="image/cexiugai01.jpg" download="cexiugai01.jpg">图片下载</a></p>
    <p><a href="image/公共课复习材料001.docx">word文档下载(带中文)</a></p>
    <p><a href="download.do">word文档下载(控制器)</a></p>
</html>

可能会遇到的问题:路径中含有中文参数

解决办法:配置tomcat的编码方式,即修改server.xml文件,加上URIEncoding="utf-8";大约在65行的位置,然后重启服务器

<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8084" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="utf-8"/>

2.编写控制层方法,返回ResponseEntity<byte[]>对象

@RequestMapping("download.do")
         public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
             
             ServletContext servletContext = request.getServletContext();
             
             String fileName="公共课复习材料001.docx";
             
             String realPath = servletContext.getRealPath("/image/"+fileName);//得到文件所在位置
             
             System.out.println("路径:"+realPath);
             
             InputStream in=new FileInputStream(new File(realPath));//将该文件加入到输入流之中
             
             byte[] body=null;
             

            // 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数          

             body=new byte[in.available()];

             
             in.read(body);//读入到输入流里面
             
             fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文乱码
             
             HttpHeaders headers=new HttpHeaders();//设置响应头
             
             headers.add("Content-Disposition", "attachment;filename="+fileName);
             
             HttpStatus statusCode = HttpStatus.OK;//设置响应码
             
             ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
             
             return response;
        
         }

说明:浏览器对于一些文件下载时会直接打开,比如图片,如果想避免这样的情况,可以在超链接标签上加上一个downd属性,

值为文件名。






猜你喜欢

转载自blog.csdn.net/weixin_40655220/article/details/79312202