springmvc 上传文件步骤:
第一 拷贝所需jar
第二 需要在springmvc(springmvc-servlet.xml)中配置:SpringMVC上传文件时,需要配置MultipartResolver处理器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="200000"/>
</bean>
第三 需要在上传的表单添加enctype="multipart/form-data"
<form method="post" enctype="multipart/form-data" action="upload.do">
<input type="file" name="file" /> <br/>
<input type="submit" /> <br/>
</form>
第四 单个文件上传
@RequestMapping(value = "/upload.do")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request, ModelMap model) {
// 上传地址
String path = request.getSession().getServletContext()
.getRealPath("\\upload\\");
String fileName = file.getOriginalFilename();
File targetFile = new File(path, new Random().nextInt(100) + fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
return "index";
}
第五 多个文件上传
// 多文件上传
@RequestMapping(value = "/upload1.do")
public String fileUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
String ctxPath = request.getSession().getServletContext()
.getRealPath("\\upload\\");
File file = new File(ctxPath);
if (!file.exists()) {
file.mkdir();
}
System.out.println(fileMap.size());
String fileName = null;
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 上传文件名
System.out.println("key: " + entity.getKey());
MultipartFile mf = entity.getValue();
fileName = mf.getOriginalFilename();
File uploadFile = new File(ctxPath + fileName);
System.out.println(ctxPath + fileName);
FileCopyUtils.copy(mf.getBytes(), uploadFile);
}
return "index";
}
注意:多文件上传的时候页面的input标签name属性的值不能相同
<form method="post" enctype="multipart/form-data" action="upload.do">
<input type="file" name="file1" /> <br/>
<input type="file" name="file2" /> <br/>
<input type="submit" /> <br/>
</form>