SpringMVC(四)---文件上传与下载

一,文件上传

文件上传是项目开发中最常见的功能之一 ,springMVC 可以很好的支持文件上传,但是SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况下其不能处理文件上传工作

如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver

1,文件配置及导包

对springmvc-servlet.xml进行文件配置

1 <!--文件上传配置-->
2     <bean id="multipartResolver"
3           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4         <property name="defaultEncoding" value="utf-8"/>
5         <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
6         <property name="maxUploadSize" value="1048576"/>
7         <property name="maxInMemorySize" value="40960"/>
8     </bean>

2,前端 upload.jsp

为了能上传文件,必须将表单的method设置为post,并将enctype设置为multipart/form-data;只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <body>
 4 
 5 <form action="${pageContext.request.contextPath}/upload1" 
 6                enctype="multipart/form-data" method="post">
 7     <p> 上传 文件:<input type="file" name="file"/></p>
 8     <p><input type="submit" value="上传"></p>
 9 </form>
10 
11 </body>
12 </html>

(1)采用流的方式上传文件

@RequestParam(" file ") 将name = file控件得到的文件封装成CommonsMultipartFile对象;批量上传CommonsMultipartFile则为数组即可

CommonsMultipartFile的常用方法:

  • String getOriginalFilename():获取上传文件的原名
  • InputStream getInputStream():获取文件流
  • void transferTo(File dest):将上传文件保存到一个目录文件中

代码

 1 @Controller
 2 public class ControllerUpload {
 3 
 4     @RequestMapping("/upload1")
 5     public String fileUpload(@RequestParam("file") CommonsMultipartFile file,
 6                                          HttpServletRequest request) throws IOException {
 7 
 8         //1.获取文件名字
 9         String uploadName = file.getOriginalFilename();
10         //2.如果文件名为空则返回首页
11         if ("".equals(uploadName)) {
12             return "redirect:/index.jsp";
13         }
14         System.out.println("上传的文件名:" + uploadName);
15 
16         //3.上传路径保存设置
17         String path = request.getServletContext().getRealPath("/WEB-INF/upload1");
18         //4.如果路径不存在就创建一个
19         File realPath = new File(path);
20         if (!realPath.exists()) {
21             realPath.mkdir();
22         }
23         System.out.println("保存的路径名:" + realPath);
24 
25         //5.文件输入流
26         InputStream in = file.getInputStream();
27         //6.文件输入流
28         FileOutputStream out = new FileOutputStream(new File(realPath, uploadName));
29 
30         //7.读取
31         int len = 0;
32         byte[] bytes = new byte[1024];
33         while ((len = in.read(bytes)) != -1) {
34             out.write(bytes, 0, len);
35             out.flush();
36         }
37         out.close();
38         in.close();
39 
40         return "redirect:/success.jsp";
41     }
42 }

运行测试

保存的位置

(2)采用file.Transto 来上传

代码

 1 @Controller
 2 public class ControllerUpload {
 3 
 4     @RequestMapping("/upload2")
 5     public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, 
 6                                        HttpServletRequest request) throws IOException {
 7 
 8         //上传路径保存设置
 9         String path = request.getServletContext().getRealPath("/WEB-INF/upload2");
10         File realPath = new File(path);
11         if (!realPath.exists()) {
12             realPath.mkdir();
13         }
14 
15         //上传文件地址
16         System.out.println("上传文件保存地址:" + realPath);
17 
18         //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
19         file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
20 
21         return "redirect:/success.jsp";
22     }
23 }

【注意点:这里我们有两种方式显示上传成功的界面,第一种就是像我一样新建一个成功的success .jsp;

然后上传成功后让它重定向到成功界面。第二种就是运行JSON,在controller中加上@ResponseBody,并且return一句话,这样上传成功后就会直接显示出你return的话】

二,文件下载

1,前端 download.jsp

1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 <html>
3 <body>
4 
5 <a href="${pageContext.request.contextPath}/download">下载图片</a>
6 
7 </body>
8 </html>

2,controller代码

  1. 设置 response 响应头
  2. 读取文件 -- InputStream
  3. 写出文件 -- OutputStream
  4. 执行操作
  5. 关闭流 (先开后关)
 1 @Controller
 2 public class ControllerDownload {
 3 
 4     @RequestMapping("/download")
 5     public String downloads(HttpServletResponse response) throws Exception{
 6 
 7         //1.要下载的图片地址
 8         String path="F:\\图片";
 9         String  fileName = "9.jpg";
10 
11         //2.设置response 响应头
12         response.reset(); //设置页面不缓存,清空buffer
13         response.setCharacterEncoding("UTF-8"); //字符编码
14         response.setContentType("multipart/form-data"); //二进制传输数据
15         //3.设置响应头
16         response.setHeader("Content-Disposition",
17                 "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
18 
19         File file = new File(path,fileName);
20         //4.读取文件--输入流
21         InputStream input=new FileInputStream(file);
22         //5.写出文件--输出流
23         OutputStream out = response.getOutputStream();
24 
25         byte[] buff =new byte[1024];
26         int index=0;
27         //6.执行 写出操作
28         while((index= input.read(buff))!= -1){
29             out.write(buff, 0, index);
30             out.flush();
31         }
32         out.close();
33         input.close();
34         return null;
35     }
36 }

运行测试

猜你喜欢

转载自www.cnblogs.com/tqsh/p/11297777.html