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

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

1.上传需要jar包    commons-fileupload.jar   commons-io.jar

2.使用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">
<property name="defaultEncoding" value="UTF-8" />
<property name="maxUploadSize" value="2097152" />
</bean>
</beans>

3.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()">
上传人:<input id="name" type="text" name="name"/><br/>
请选择文件:<input id="file" type="file" name="uploadfile" multiple="multiple"/><br/>
<%--multiple属性选择多个文件上传--%>
<input type="submit" value="文件上传" />
</form>
</body>
</html>

4.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>

5.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");
}
}

最新文章

  1. input file限制上传文件类型
  2. Selenium+python 配置
  3. Discrete.Differential.Geometry-An.Applied.Introduction(sig2013) 笔记
  4. X64下MmIsAddressValid的逆向及内存寻址解析
  5. Clappr——开源的Web视频播放器
  6. CUBRID学习笔记 32 对net的datatable的支持 cubrid教程
  7. jquery事件切换hover/toggle
  8. 【Irrlicht鬼火引擎】 安装配置Irrlicht鬼火引擎
  9. javaScript创建无边框iframe兼容ie
  10. Linux中tar命令-C用法
  11. jQuery之异步Ajax请求使用
  12. codevs 2152 滑雪
  13. uva 10963 - The Swallowing Ground
  14. mysql dos启动出现1067错误的解决方法
  15. java static关键字
  16. BigDecimal类的简单使用方法
  17. BZOJ 4321: queue2( dp )
  18. (简单) POJ 3074 Sudoku, DLX+精确覆盖。
  19. [PHP] PHP1 与 CGI
  20. JAVA面试一

热门文章

  1. 交通规则:HOV车道
  2. Java基础00-Java概述1
  3. Python爬虫下载酷狗音乐
  4. robotframework - PO设计
  5. python3执行.sql文件
  6. NumPy之:多维数组中的线性代数
  7. 流畅的python--函数
  8. document.all(&quot;div).style.display = &quot;none&quot;与 等于&quot;&quot;的区别
  9. Mybatis学习笔记-注解开发
  10. 查看filesystem type及ftype的值