SpringMVC文件上传和下载的实现

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

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

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

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.wxy.controller"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<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>
</beans>

2.fileUpload.jsp上传页面

 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
<script>
<%--判断是否填写上传人并已经选择上传文件--%>
function check() {
var name = document.getElementById("name").value();
var name = document.getElementById("file").value();
if(name==""){
alert("请填写上传人");
return false;
}
if(file.length==0||file==""){
alert("请选择上传文件");
return false;
}
return true;
}
</script>
</head>
<body>
<%--enctype="multipart/form-data"采用二进制流处理表单数据--%>
<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>
</body>
</html>

3.fileDownload.jsp下载页面

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

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

 package com.wxy.controller;

 import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID; @Controller("controller")
public class FileUploadAndDownloadController {
@RequestMapping("/tofileUpload")
public String toupload(){
return "fileUpload";
}
@RequestMapping("/tofiledownload")
public String todownload(){
return "download";
}
@RequestMapping("/fileUpload.action")
public String handleFormUpload(@RequestParam("name") String name,
@RequestParam("uploadfile") List<MultipartFile> uploadfile, HttpServletRequest request) {
if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
for (MultipartFile file : uploadfile) {
String originalFilename = file.getOriginalFilename();
String dirPath = request.getServletContext().getRealPath("/upload/");
File filePath = new File(dirPath);
if (!filePath.exists()) {
filePath.mkdirs();
} String newFilename = name +"_" + originalFilename;
try {
file.transferTo(new File(dirPath + "_"+newFilename));
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
return "success";
} else {
return "error";
}
}
@RequestMapping("/download.action")
public ResponseEntity<byte[]> filedownload(HttpServletRequest request,String filename) throws Exception{
String path = request.getServletContext().getRealPath("/upload");
File file = new File(path+File.separator+filename);
filename = this.getFilename(request,filename);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment",filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}
public String getFilename(HttpServletRequest request,String filename) throws Exception{
String[] IEBrowserKeyWord = {"MSIE","Trident","Edge"};
String userAgent = request.getHeader("User-Agent");
for(String keyWord:IEBrowserKeyWord){
if(userAgent.contains(keyWord)){
return URLEncoder.encode(filename,"UTF-8");
}
}
return new String(filename.getBytes("UTF-8"),"ISO-8859-1");
}
}

FileUploadAndDownloadController

上一篇:uva 10976 fractions again(水题)——yhx


下一篇:JRoll 2 使用文档(史上最强大的下拉刷新,滚动,无限加载插件)