首页 > 代码库 > SpringMVC实现从磁盘中下载文件

SpringMVC实现从磁盘中下载文件

除了文件的上传我们还需要从磁盘下载

实现文件的下载只要编写一个控制器,完成读写操作和响应头和数据类型的设置就可以了

下面演示的是从G盘imgs文件夹中下载文件

具体代码如下

 1 package com.cqupt.dayday;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import java.io.*;
 9 
10 /**
11  * Created by I am master on 2017/5/16.
12  */
13 @Controller
14 public class ResourceController {
15     @RequestMapping("/download")
16     public String download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
17         response.setCharacterEncoding("utf-8");
18         //返回的数据类型
19         response.setContentType("application/pdf");
20         //响应头
21         response.setHeader("Content-Disposition", "attachment;fileName="
22                 + fileName);
23         InputStream inputStream=null;
24         OutputStream outputStream=null;
25         //路径
26         String path ="G:"+ File.separator+"imgs"+File.separator;
27         byte[] bytes = new byte[2048];
28         try {
29             File file=new File(path,fileName);
30             inputStream = new FileInputStream(file);
31             outputStream = response.getOutputStream();
32             int length;
33             //inputStream.read(bytes)从file中读取数据,-1是读取完的标志
34             while ((length = inputStream.read(bytes)) > 0) {
35                 //写数据
36                 outputStream.write(bytes, 0, length);
37             }
38         } catch (FileNotFoundException e) {
39             e.printStackTrace();
40         } catch (IOException e) {
41             e.printStackTrace();
42         }finally {
43             //关闭输入输出流
44             if(outputStream!=null) {
45                 outputStream.close();
46             }
47             if(inputStream!=null) {
48                 inputStream.close();
49             }
50         }
51         return null;
52     }
53 }

用了注解进行描述就不在重复了

在写的过程中遇到的问题:FileNotFoundException

原因:路径不正确

一定要注意路径问题在写的时候

前端代码:

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7       <center><h1>Download Page</h1></center>
 8       <a href="http://www.mamicode.com/download?fileName=B.pdf">B.pdf</a>
 9  </body>
10 </html>

 

测试页面:

技术分享

点击即完成下载

技术分享

 

SpringMVC实现从磁盘中下载文件