springMVC相关-文件下载

1.加入jar包:
        commons-fileupload-1.3.1.jar
        commons-io-2.4.jar2.<a href="${pageContext.request.contextPath }/testdownload">文件下载</a><br/>

用ResponseEntity<byte[]> 返回值完成文件下载:

   @RequestMapping(value="/testResponseEntity")
            public ResponseEntity<byte[]> testResponseEntity(HttpServletRequest request) throws Exception{
                byte[] body = null;
                ServletContext servletContext = request.getServletContext();
                String fileName = "风吹麦浪.mp3";
                
                String path = servletContext.getRealPath("/WEB-INF/"+fileName);
                File file = new File(path);
                InputStream in = new FileInputStream(file);
                body = new byte[in.available()];
                in.read(body);
                HttpHeaders headers = new HttpHeaders();
                fileName = new String(fileName.getBytes("gbk"),"iso8859-1");
                headers.add("Content-Disposition", "attachment;filename="+fileName);
                HttpStatus statusCode=HttpStatus.OK;
                ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
                
                return response;
            }    

 其中,ResponseEntity<byte[]>代替输出流作用。

通过标签(如<a>)链接到该方法,执行后浏览器页面显示对风吹麦浪.mp3的下载窗口。(风吹麦浪.mp3音频文件位于服务器WEB-INF目录下,不被浏览器直接访问)

原文地址:https://www.cnblogs.com/kangxingyue-210/p/7424005.html