1.通过commons-fileupload来实现。导入相关jar包
2.配置springmvc解析器
<bean id = "multipartResolver" class="org.springframework.web.multipart.commons.CommonsMuiltipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
3.jsp页面
<form action="upload.do" method="post" enctype="multipart/form-data">
file1:<input type="file" name="file" />
file2:<input type="file" name="file" />
<input type="submit" value="上传" />
</form>
4.Controller
@Controller
@RequestMapping("/fileController")
public class FileUploadController {
@RequestMapping("/upload.do")
public String fileupload(@RequestParam("file")CommonsMultipartFile file[], HttpServletRequest request) throws IOException {
for(int i = 0 ; i < file.length;++i) {
InputStream is = file[i].getInputStream();
OutputStream os = new FileOutputStream(new File("/Users/limbo/Documents",file[i].getOriginalFilename()));
int len = 0 ;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
os.close();
is.close();
}
return "/index.jsp";
}
}
注意:上面我写的是批量上传。下面讲一下我写这个东西遇到的坑吧
Spring mvc: HTTP Status 400 - Required MultipartFile parameter 'file' is not present
很有可能是你没有写配置文件,或者是配置文件里面的类出了问题
还有一个坑,就是我用的是intellij,如果你直接在lib文件里面添加jar文件的话,会出现ClassNotFound的问题,要在File->Project Structure里面在把东西配置进去!
我建议还是看看我另外两篇,感觉直接用fileupload更加好吧