配置CommonsMultipartResolver
<bean id ="multipartResolver"
class ="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name ="maxUploadSize" value ="100000" />
</bean >
@Autowired
private HttpServletRequest request;
/***
* 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
*
* @param file
* @return
*/
@RequestMapping ("fileUpload" )
public String fileUpload (@RequestParam ("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
String filePath = request.getSession().getServletContext().getRealPath("/" ) + "upload/"
+ file.getOriginalFilename();
file.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
return "redirect:/list.html" ;
}
/***
* 读取上传文件中得所有文件并返回
*
* @return
*/
@RequestMapping ("list" )
public ModelAndView list () {
String filePath = request.getSession().getServletContext().getRealPath("/" ) + "upload/" ;
ModelAndView mav = new ModelAndView("list" );
File uploadDest = new File(filePath);
String[] fileNames = uploadDest.list();
for (int i = 0 ; i < fileNames.length; i++) {
System.out.println(fileNames[i]);
}
return mav;
}