http://tzwzero-163-com.iteye.com/blog/1697184
必须明确告诉DispatcherServlet如何处理MultipartRequest。
SpringMVC中提供了文件上传使用方式如下
配置xxx-servlet.xml,添加如下代码:
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- 设置上传文件的最大尺寸为1MB -->
- <property name="maxUploadSize">
- <value>1048576</value>
- </property>
- </bean>
注意这里的文件尺寸实际上只的是所以文件总大小
如果配置了文件大小就以为这你需要配置异常信息控制
所以需要配置异常显示
- <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
- <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
- <bean id="exceptionResolver"
- class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <property name="exceptionMappings">
- <props>
- <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->
- <prop
- key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
- </props>
- </property>
- </bean>
或者偷懒点,不设置大小,则最终默认是值为不限制。如果非要控制返回信息,可以考虑在地应以的异常处理中返回指定格式数据,例如JSON
配置完了页面上一如既往的需要再form表单中增加:enctype="multipart/form-data"
然后就是需要处理的action了,可以有两种方式
第一种方式:
- public String login( @RequestParam MultipartFile file, Model model) {
- ………………
- }
其中file的名字必须保证与<input type=file>中的那么属性值保持一致,若果是多文件上传,则考虑使用
- public String login(@Valid UserInfo userInfo, BindingResult result, @RequestParam MultipartFile[] files, Model model) {
- ………………
- }
单文件可以省略 @RequestParam 多文件则不可省略
第二种方式:
- public ModelAndView handleRequest(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- // 转型为MultipartHttpRequest:
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- // 获得文件:
- MultipartFile file = multipartRequest.getFile(" file ");
- }
这样也可以获取到文件
其实刚才首先需要配置是加入两个 jar包:
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
http://blog.csdn.net/a1314517love/article/details/24183273
springMVC实现多文件上传的方式有两种,一种是我们经常使用的以字节流的方式进行文件上传,另外一种是使用springMVC包装好的解析器进行上传
package com.tgb.web.controller.annotation.upload;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileNameExtensionFilter;
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.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
import com.tgb.web.controller.entity.User;
@Controller
@RequestMapping("/file")
public class UploadController {
@RequestMapping("/upload" )
public String addUser(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request){
for(int i = 0;i<files.length;i++){
System.out.println("fileName---------->" + files[i].getOriginalFilename());
if(!files[i].isEmpty()){
int pre = (int) System.currentTimeMillis();
try {
//拿到输出流,同时重命名上传的文件
FileOutputStream os = new FileOutputStream("H:/" + new Date().getTime() + files[i].getOriginalFilename());
//拿到上传文件的输入流
FileInputStream in = (FileInputStream) files[i].getInputStream();
//以写字节的方式写文件
int b = 0;
while((b=in.read()) != -1){
os.write(b);
}
os.flush();
os.close();
in.close();
int finaltime = (int) System.currentTimeMillis();
System.out.println(finaltime - pre);
} catch (Exception e) {
e.printStackTrace();
System.out.println("上传出错");
}
}
}
return "/success";
}
@RequestMapping("/upload2" )
public String upload2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
//记录上传过程起始时的时间,用来计算上传时间
int pre = (int) System.currentTimeMillis();
//取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if(file != null){
//取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
//如果名称不为“”,说明该文件存在,否则说明该文件不存在
if(myFileName.trim() !=""){
System.out.println(myFileName);
//重命名上传后的文件名
String fileName = "demoUpload" + file.getOriginalFilename();
//定义上传路径
String path = "H:/" + fileName;
File localFile = new File(path);
file.transferTo(localFile);
}
}
//记录上传该文件后的时间
int finaltime = (int) System.currentTimeMillis();
System.out.println(finaltime - pre);
}
}
return "/success";
}
@RequestMapping("/toUpload" )
public String toUpload() {
return "/upload";
}
}
至此,上传结束
下载
public static ResponseEntity<byte[]> genPdfFile(byte[] excelBytes, String fileName, String charset,final HttpServletRequest request){
//编码格式
String strCharset = !StringUtil.isBlank(charset) ? charset : "UTF-8";
//禁止缓存
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.parseMediaType("application/octet-stream;charset="+strCharset));
responseHeaders.setPragma("No-cache");
responseHeaders.setCacheControl("No-cache");
responseHeaders.setExpires(0);
String strFileName = String.format("%s.pdf", !StringUtil.isBlank(fileName) ? fileName : "协议");
try{
//iso-8859-1解决中文乱码
final String agent = request.getHeader("User-Agent");
final boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
if(isMSIE){
strFileName = URLEncoder.encode(strFileName,"UTF8");
}else{
strFileName = new String(strFileName.getBytes("UTF-8"),"iso-8859-1");
}
responseHeaders.setContentDispositionFormData("attachment", strFileName);
return new ResponseEntity<byte[]>(excelBytes, responseHeaders, HttpStatus.OK);
} catch(Exception e){
LOGGER.fatal("genPdfFile failed", e);
return null;
}
}