码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC文件上传和下载的实现

时间:2018-04-08 00:17:21      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:method   支持   element   common   多个   bytearray   head   isp   gpo   

SpringMVC通过MultipartResolver(多部件解析器)对象实现对文件上传的支持。

MultipartResolver是一个接口对象,需要通过它的实现类CommonsMultipartResolver来完成文件的上传工作。

1.使用MultipartResolver对象,在XML中配置Bean.

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans
 6        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
 7        http://www.springframework.org/schema/context
 8        http://www.springframework.org/schema/context/spring-context-4.3.xsd">
 9     <context:annotation-config/>
10     <context:component-scan base-package="com.wxy.controller"/>
11     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
12         <property name="prefix" value="/WEB-INF/jsp/"></property>
13         <property name="suffix" value=".jsp"></property>
14     </bean>
15     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
16         <property name="defaultEncoding" value="UTF-8" />
17         <property name="maxUploadSize" value="2097152" />
18     </bean>
19 </beans>

2.fileUpload.jsp上传页面

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>文件上传</title>
 5     <script>
 6         <%--判断是否填写上传人并已经选择上传文件--%>
 7         function check() {
 8             var name = document.getElementById("name").value();
 9             var name = document.getElementById("file").value();
10             if(name==""){
11                 alert("请填写上传人");
12                 return false;
13             }
14             if(file.length==0||file==""){
15                 alert("请选择上传文件");
16                 return false;
17             }
18             return true;
19         }
20     </script>
21 </head>
22 <body>
23 <%--enctype="multipart/form-data"采用二进制流处理表单数据--%>
24 <form action="${pageContext.request.contextPath}/fileUpload.action" method="post" enctype="multipart/form-data" onsubmit="return check()">
25     上传人:<input id="name" type="text" name="name"/><br/>
26     请选择文件:<input id="file" type="file" name="uploadfile" multiple="multiple"/><br/>
27     <%--multiple属性选择多个文件上传--%>
28     <input type="submit" value="文件上传" />
29 </form>
30 </body>
31 </html>

3.fileDownload.jsp下载页面

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
 2 <%@ page import="java.net.URLEncoder" %>
 3 <html>
 4 <head>
 5     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 6     <title>文件下载</title>
 7 </head>
 8 <body>
 9 <a href="${pageContext.request.contextPath}/download.action?filename=<%=URLEncoder.encode("图像.txt","UTF-8")%>">文件下载</a>
10 </body>
11 </html>

4.FileUploadAndDownloadController.java文件上传和下载控制器类

技术分享图片
 1 package com.wxy.controller;
 2 
 3 import org.apache.commons.io.FileUtils;
 4 import org.springframework.http.HttpHeaders;
 5 import org.springframework.http.HttpStatus;
 6 import org.springframework.http.MediaType;
 7 import org.springframework.http.ResponseEntity;
 8 import org.springframework.stereotype.Controller;
 9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.RequestParam;
11 import org.springframework.web.multipart.MultipartFile;
12 
13 import javax.servlet.http.HttpServletRequest;
14 import java.io.File;
15 import java.net.URLEncoder;
16 import java.util.List;
17 import java.util.UUID;
18 
19 @Controller("controller")
20 public class FileUploadAndDownloadController {
21     @RequestMapping("/tofileUpload")
22     public String toupload(){
23         return "fileUpload";
24     }
25     @RequestMapping("/tofiledownload")
26     public String todownload(){
27         return "download";
28     }
29     @RequestMapping("/fileUpload.action")
30     public String handleFormUpload(@RequestParam("name") String name,
31                                    @RequestParam("uploadfile") List<MultipartFile> uploadfile, HttpServletRequest request) {
32         if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
33             for (MultipartFile file : uploadfile) {
34                 String originalFilename = file.getOriginalFilename();
35                 String dirPath = request.getServletContext().getRealPath("/upload/");
36                 File filePath = new File(dirPath);
37                 if (!filePath.exists()) {
38                     filePath.mkdirs();
39                 }
40 
41                 String newFilename = name +"_" + originalFilename;
42                 try {
43                     file.transferTo(new File(dirPath + "_"+newFilename));
44                 } catch (Exception e) {
45                     e.printStackTrace();
46                     return "error";
47                 }
48             }
49             return "success";
50         } else {
51             return "error";
52         }
53     }
54     @RequestMapping("/download.action")
55     public ResponseEntity<byte[]> filedownload(HttpServletRequest request,String filename) throws Exception{
56         String path = request.getServletContext().getRealPath("/upload");
57         File file = new File(path+File.separator+filename);
58         filename = this.getFilename(request,filename);
59         HttpHeaders headers = new HttpHeaders();
60         headers.setContentDispositionFormData("attachment",filename);
61         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
62         return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
63     }
64     public String getFilename(HttpServletRequest request,String filename) throws Exception{
65         String[] IEBrowserKeyWord = {"MSIE","Trident","Edge"};
66         String userAgent = request.getHeader("User-Agent");
67         for(String keyWord:IEBrowserKeyWord){
68             if(userAgent.contains(keyWord)){
69                 return URLEncoder.encode(filename,"UTF-8");
70             }
71         }
72         return new String(filename.getBytes("UTF-8"),"ISO-8859-1");
73     }
74 }
FileUploadAndDownloadController

 

SpringMVC文件上传和下载的实现

标签:method   支持   element   common   多个   bytearray   head   isp   gpo   

原文地址:https://www.cnblogs.com/wxywxy/p/8724107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!