commonsmultipartresolver 的源码,可以研究一下 点我
前端代码:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form name="serForm" action="/SpringMVC006/fileUpload" method="post" enctype="multipart/form-data">
<h1>采用流的方式上传文件</h1>
<input type="file" name="file">
<input type="submit" value="upload"/>
</form>
<form name="Form2" action="/SpringMVC006/fileUpload2" method="post" enctype="multipart/form-data">
<h1>采用multipart提供的file.transfer方法上传文件</h1>
<input type="file" name="file">
<input type="submit" value="upload"/>
</form>
<form name="Form2" action="/SpringMVC006/springUpload" method="post" enctype="multipart/form-data">
<h1>使用spring mvc提供的类的方法上传文件</h1>
<input type="file" name="file">
<input type="submit" value="upload"/>
</form>
</body>
</html>
配置代码:
<!-- 多部分文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传图片最大大小100M(5M 5242440)-->
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<!-- 设置默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
pom添加依赖:
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
后台代码:
方式一:
/*
* 通过流的方式上传文件
* @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
*/
@RequestMapping("fileUpload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException {
//用来检测程序运行时间
long startTime=System.currentTimeMillis();
System.out.println("fileName:"+file.getOriginalFilename());
try {
//获取输出流
OutputStream os=new FileOutputStream("E:/"+new Date().getTime()+file.getOriginalFilename());
//获取输入流 CommonsMultipartFile 中可以直接得到文件的流
InputStream is=file.getInputStream();
int temp;
//一个一个字节的读取并写入
while((temp=is.read())!=(-1))
{
os.write(temp);
}
os.flush();
os.close();
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long endTime=System.currentTimeMillis();
System.out.println("方法一的运行时间:"+String.valueOf(endTime-startTime)+"ms");
return "/success";
}
方式二:
/*
* 采用file.Transto 来保存上传的文件
*/
@RequestMapping("fileUpload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file) throws IOException {
long startTime=System.currentTimeMillis();
System.out.println("fileName:"+file.getOriginalFilename());
String path="E:/"+new Date().getTime()+file.getOriginalFilename();
File newFile=new File(path);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(newFile);
long endTime=System.currentTimeMillis();
System.out.println("方法二的运行时间:"+String.valueOf(endTime-startTime)+"ms");
return "/success";
}
方式三:
/*
*采用spring提供的上传文件的方法
*/
@RequestMapping("springUpload")
public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException
{
long startTime=System.currentTimeMillis();
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request))
{
//将request变成多部分request
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
//获取multiRequest 中所有的文件名
Iterator iter=multiRequest.getFileNames();
while(iter.hasNext())
{
//一次遍历所有文件
MultipartFile file=multiRequest.getFile(iter.next().toString());
if(file!=null)
{
String path="E:/springUpload"+file.getOriginalFilename();
//上传
file.transferTo(new File(path));
}
}
}
long endTime=System.currentTimeMillis();
System.out.println("方法三的运行时间:"+String.valueOf(endTime-startTime)+"ms");
return "/success";
}
我们看看测试上传的时间:
第一次我用一个4M的文件:
fileName:test.rar
方法一的运行时间:14712ms
方法二的运行时间:5ms
方法三的运行时间:4ms
第二次:我用一个50M的文件
方式一进度很慢,估计得要个5分钟
方法二的运行时间:67ms
方法三的运行时间:80ms
从测试结果我们可以看到:用springMVC自带的上传文件的方法要快的多!
对于测试二的结果:可能是方法三得挨个搜索,所以要慢点。不过一般情况下我们是方法三,因为他能提供给我们更多的方法。
附文件:
package com.datebook.web;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.datebook.common.JsonResult;
import com.datebook.common.ResultCode;
@RestController
@RequestMapping("/file")
public class FileController {
// 上传新的图像,删除原来的图像
/* UserInfoBean item = userService.loadUserInfoByUid(tmpuser.getUid());
* File df = new File(rootPath + item.getImgpath());
if (df.exists()) {
df.delete();
}*/
/**
* 单文件上传
*/
@RequestMapping("/oneFileUpload")
public JsonResult singleFileUpload(@RequestParam("file1")MultipartFile file1,HttpServletRequest request) throws Exception, IOException {
String filePath = request.getServletContext().getRealPath("upload");
String filename = file1.getOriginalFilename();
System.out.println("----------------------"+filePath+"------------------------");
File targetFile = new File(filePath,filename);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file1.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
//文件路径
String fullPath = targetFile.getPath();
String path = "upload/" + filename;
Map<String, Object> map = new HashMap<>();
map.put("filePath", path);
map.put("fullPath", fullPath);
return new JsonResult(ResultCode.SUCCESS,"success",map);
}
/**
* 多文件上传
*/
@RequestMapping("/multipleFileUpload")
public JsonResult multipleFileUpload(@RequestParam("files")MultipartFile[] files,HttpServletRequest request) throws Exception, IOException {
String filePath = request.getServletContext().getRealPath("upload");
System.out.println("----------------------"+filePath+"------------------------");
List<String> path = new ArrayList<>();
List<String> fullPath = new ArrayList<>();
for(MultipartFile file:files){
String filename = file.getOriginalFilename();
File targetFile = new File(filePath,filename);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
/* String path1 = "upload/" + filename;
String path2 = targetFile.getPath();*/
path.add("upload/" + filename);
fullPath.add(targetFile.getPath());
}
Map<String, Object> map = new HashMap<>();
map.put("filePath", path);
map.put("fullPath", fullPath);
return new JsonResult(ResultCode.SUCCESS,"success",map);
}
/**
* 流上传
*/
@RequestMapping(value = "requestFile", method = RequestMethod.POST)
public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {
// 转型为MultipartHttpRequest:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获得文件:
MultipartFile file = multipartRequest.getFile("file");
// 获得文件名:
String filename = file.getOriginalFilename();
// 获得输入流:
InputStream input = file.getInputStream();
// 写入文件
file.transferTo(new File("E://"+filename));
System.out.println(filename);
return null;
}
@RequestMapping("/fileDownload1")
public ResponseEntity<byte[]> filedDownload1() throws IOException {
//下载文件路径
String path="E:\\xiaomao.jpg";
File file=new File(path);
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
String fileName=new String("小猫.jpg".getBytes("UTF-8"),"iso-8859-1");
//通知浏览器以attachment(下载方式)打开图片
headers.setContentDispositionFormData("attachment", fileName);
//application/octet-stream : 二进制流数据(最常见的文件下载)
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
@RequestMapping("/fileDownload2")
public void fileDownload2(HttpServletRequest request,HttpServletResponse response) throws Exception{
//模拟文件,xiaomao.jpg为需要下载的文件
String fileName = request.getSession().getServletContext().getRealPath("upload")+"/xiaomao.jpg";
//获取输入流
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
//假如以中文名下载的话
String filename = "xiaomao.jpg";
//转码,免得文件名中文乱码
filename = URLEncoder.encode(filename,"UTF-8");
//设置文件下载头
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while((len = bis.read()) != -1){
out.write(len);
out.flush();
}
out.close();
}
}