文件上传—传统方式,SpringMVC方式
传统方式的文件上传
<body>
<form action="/user/upload1" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br/>
<input type="submit" value="提交">
</form>
</body>
@RequestMapping("upload1")
public String upload1(HttpServletRequest request) throws Exception {
System.out.println("文件上传");
String realPath = request.getServletContext().getRealPath("/upload");
File file = new File(realPath);
if (!file.exists()){
file.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()){
}else {
String filename = item.getName();
String uuid = UUID.randomUUID().toString();
filename = uuid + "_" + filename;
item.write(new File(realPath,filename));
item.delete();
}
}
return "redirect:/success.jsp";
}
SpringMVC的文件上传
<form action="/user/upload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br/> <%--注意:name的值必须和后台方法的形参名一致--%>
<input type="submit" value="提交">
</form>
@RequestMapping("upload2")
public String upload2(HttpServletRequest request, MultipartFile upload) throws Exception {
String realPath = request.getServletContext().getRealPath("/upload");
File file = new File(realPath);
if (!file.exists()){
file.mkdirs();
}
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString();
filename = uuid + "_" + filename;
upload.transferTo(new File(realPath,filename));
return "redirect:/success.jsp";
}
在springmvc.xml配置文件上传的组件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"></property>
</bean>