springmvc上传文件源码分享
解决方法:
1.springmvc的配置文件添加:
<!-- 上传文件拦截,设置最大上传文件大小 100M=10*1024*1024(B)=1048576000 bytes -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576000" />
</bean>
2.核心方法
@RequestMapping("/upload")
public void toUpload(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request,HttpServletResponse response) throws Exception{
HashMap<String, Object> context = new HashMap<String, Object>();
try{
for(CommonsMultipartFile file:files){
String dir = request.getSession().getServletContext().getRealPath("/")+"upload/";
File dirFile = new File(dir);
//如果路径不存在,新建
if(!dirFile.exists()&&!dirFile.isDirectory()) {
dirFile.mkdirs();
}
String path=dir+"/"+file.getOriginalFilename();
File newFile=new File(path);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(newFile);
}
String jsonString = JSONUtil.toJSONString(context);
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(jsonString);
} catch (Exception e) {
//上传异常,删除临时文件
context.put("state", "fail");
String jsonString = JSONUtil.toJSONString(context);
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(jsonString);
}
}