此篇博客是关于使用springMVC进行文件上传的。
1.在springMVC-servlet.xml中添加相关的Bean,如下:
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="10485760000"/>
<property name="defaultEncoding" value="utf-8"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
2.添加相关jar包,分别是:
com.springsource.org.apache.commons.fileupload-1.2.0.jar
com.springsource.org.apache.commons.io-1.4.0.jar
3.文件上传的jsp页面必须注意的地方,自己老是只记得要修改enctype,而忘记修改method属性为post,代码如下:
<form action="/springMVC2/file/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="上传文件">
</form>
4. Controller的代码:
package com.study.controller.annotation;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller
@RequestMapping("/file")
public class UploadController {
@RequestMapping("/upload")//@RequestParam中的file对应jsp页面中的 name="file"
public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws Exception{
String fileName = file.getOriginalFilename();//必须是这个获取文件名的函数
//System.out.println(fileName);
//System.out.println(request.getContextPath());
File storeFile = new File(request.getRealPath("storefile"));
System.out.println(storeFile.getAbsolutePath());
OutputStream os = new FileOutputStream(new File(storeFile,fileName));
InputStream is = file.getInputStream();
int b;
while((b = is.read()) != -1){
os.write(b);
}
request.setAttribute("fileName", fileName);
return "/uploadsuccess";
}
}