I.Spring MVC文件上传需要再引入名为commons-fileupload和commons-io的jar包,可在Struts2里找到所需jar包。
II.配置Spring MVC
<!-- 配置上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
III.上传
1.上传页面Fileupload.jsp
<body>
<form action="Upload.do" method="post" enctype="multipart/form-data">
file:<input type="file" name="file" />
<input type="submit" value="上传" />
</form>
</body>
2.FileuploadController
@RequestMapping("/Upload")
// 除去上传的文件,若是还有其他数据(比如name)则直接在参数中加入String name即可
// @RequestMapping("file")是必须的,否则无法初始化
public String fileUpload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest req) throws IOException {
/*
* 获取上传时文件名
* file.getOriginalFilename()
*/
// 获取上传文件的路径
String path = req.getRealPath("/FileUpload");
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(new File(path,file.getOriginalFilename()));
int len = 0;
byte[] buffer = new byte[400];
while ((len=is.read(buffer)) != -1)
os.write(buffer, 0, len);
os.close();
is.close();
return "/Index.jsp";
}
IV.批量上传Batch.jsp
1.批量上传页面Batch.jsp
<body>
<form action="Batch.do" method="post" enctype="multipart/form-data">
file:<input type="file" name="file" /><br/>
file:<input type="file" name="file" /><br/>
<input type="submit" value="上传" />
</form>
</body>
2.BatchController(使用数组就好)
@RequestMapping("/Batch")
public String fileUpload(@RequestParam("file")CommonsMultipartFile file[], HttpServletRequest req) throws IOException {
/*
* 获取上传时文件名
* file.getOriginalFilename()
*/
// 获取上传文件的路径
String path = req.getRealPath("/FileUpload");
for(int i = 0; i < file.length; i++){
InputStream is = file[i].getInputStream();
OutputStream os = new FileOutputStream(new File(path,file[i].getOriginalFilename()));
int len = 0;
byte[] buffer = new byte[400];
while ((len=is.read(buffer)) != -1)
os.write(buffer, 0, len);
os.close();
is.close();
}
return "/Index.jsp";
}