1.首先导入两个包。
2.在spring-web.xml里配置解析器。其中id的值为multipartResolver不能变。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"/>
<property name="defaultEncoding" value="utf-8"/>
</bean>
(单文件上传)
3.在jsp或者html页面的form表单中需要写一个属性enctype="multipart/form-data".
<form action="/modelmaptest/uploadfile.do" method="post" enctype="multipart/form-data">
<input type="file" name="fileItem"/><br>
<input type="submit" value="上传"/>
<p>${msg }</p>
</form>
4.在controller里接收文件,用MultipartFile类。
@Controller
public class ModelController {
@RequestMapping(value="/uploadfile.do",method=RequestMethod.POST)
public String addBook(ModelMap map,@RequestParam MultipartFile fileItem){
String filename = fileItem.getOriginalFilename();
int index = filename.lastIndexOf("\\");
if(index!=-1){
filename = filename.substring(index+1);
}
filename = UUID.randomUUID().toString()+"_"+filename;
String savepath = "F:/apache-tomcat-7.0.69/webapps/appImages";
File destFile = new File(savepath,filename);
try {
fileItem.transferTo(destFile);
map.addAttribute("msg","上传成功!");
} catch (Exception e) {
map.addAttribute("msg","上传失败!");
e.printStackTrace();
}
return "/index.jsp";
}
}
多文件上传和单文件类似,jsp页面的文件name属性都得一样才行。
<form action="/modelmaptest/uploadfile.do" method="post" enctype="multipart/form-data">
<input type="file" name="fileItem"/><br>
<input type="file" name="fileItem"/><br>
<input type="submit" value="上传"/>
<p>${msg }</p>
</form>
在controller里边就需要用数组来接收了,此处是接收两个文件用file[index]接收,还可以用遍历数组的方式来接收所有文件,根据需求即可。
@RequestMapping(value="/uploadfile.do",method=RequestMethod.POST)
public String addBook(ModelMap map,@RequestParam MultipartFile[] fileItem){
String filename = fileItem[0].getOriginalFilename();
int index = filename.lastIndexOf("\\");
if(index!=-1){
filename = filename.substring(index+1);
}
filename = UUID.randomUUID().toString()+"_"+filename;
String savepath = "F:/apache-tomcat-7.0.69/webapps/appImages";
File destFile = new File(savepath,filename);
try {
fileItem[0].transferTo(destFile);
map.addAttribute("msg","上传成功!");
} catch (Exception e) {
map.addAttribute("msg","上传失败!");
e.printStackTrace();
}
filename = fileItem[1].getOriginalFilename();
index = filename.lastIndexOf("\\");
if(index!=-1){
filename = filename.substring(index+1);
}
filename = UUID.randomUUID().toString()+"_"+filename;
destFile = new File(savepath,filename);
try {
fileItem[1].transferTo(destFile);
map.addAttribute("msg","上传成功!");
} catch (Exception e) {
map.addAttribute("msg","上传失败!");
e.printStackTrace();
}
return "/index.jsp";
}
}