配置文件放在springMVC.xml中
<!-- 文件上传: 配置multipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="100242880"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
在项目下创建upload文件夹用于放置上传到tomcat服务器的文件
文件上传controller类中的方法:
//文件上传的controller类
@RequestMapping("/testupload/upload2")
public String upload2(HttpSession session , @RequestParam("upload") CommonsMultipartFile upload) throws IOException{
ServletContext application = session.getServletContext();
//获得tomcat下upload文件夹的路径
String serverPath = application.getRealPath("upload");
System.out.println(serverPath);
uploadToServer(serverPath, upload);//调用命名方法为文件命名
return "redirect:/users/up.jsp";
}
//文件命名
private void uploadToServer(String serverPath , MultipartFile file) throws IllegalStateException, IOException{
//得到图片名
String fileName = file.getOriginalFilename();
//重命名为全球唯一的名称
String uuid = UUID.randomUUID().toString();
String extendName = fileName.substring(fileName.lastIndexOf("."),fileName.length());
String onlyName = uuid + extendName;
file.transferTo(new File(serverPath,onlyName));
}
jsp页面:
<h1>演示采用springMVC的API保存</h1>
<form action="${pageContext.request.contextPath }/testupload/upload2"
method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" /><br /> <input type="submit"
value="上传" />
</form>
多文件上传:
jsp页面:
<h1>演示多文件上传</h1>
<form action="${pageContext.request.contextPath }/testupload/upload3"
method="post" enctype="multipart/form-data">
选择文件1:<input type="file" name="upload" /><br /> 选择文件2:<input
type="file" name="upload" /><br /> 选择文件3:<input type="file"
name="file" /><br /> <input type="submit" value="上传" />
</form>
controller类:
//多文件上传的方法
@RequestMapping("/testupload/upload3")
public String upload3(HttpSession session , HttpRequest request) throws IOException{
ServletContext application = session.getServletContext();
//得到上传到服务器的图片路径
String serverPath = application.getRealPath("upload");
System.out.println(serverPath);
if(request instanceof MultipartHttpServletRequest){
MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
List<MultipartFile> files = multipart.getFiles("upload");
for (MultipartFile file : files) {
uploadToServer(serverPath, file);
}
MultipartFile file = multipart.getFile("file");
uploadToServer(serverPath, file);
}
return "redirect:/users/up.jsp";
}
//重命名文件
private void uploadToServer(String serverPath , MultipartFile file) throws IllegalStateException, IOException{
//得到图片名
String fileName = file.getOriginalFilename();
//重命名为全球唯一的名称
String uuid = UUID.randomUUID().toString();
String extendName = fileName.substring(fileName.lastIndexOf("."),fileName.length());
String onlyName = uuid + extendName;
file.transferTo(new File(serverPath,onlyName));
}