控制器中业务代码如下:
@RequestMapping(path = "/upload")
public String testupload(HttpServletRequest request)throws Exception {
String path = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(path);
File file=new File(path);
if(!file.exists())
file.mkdirs();
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
System.out.println(upload);
//解析request 获取上传文件
List<FileItem> fileItems = upload.parseRequest(request);
System.out.println(fileItems);
//判断是否是上传文件
for (FileItem fileItem : fileItems) {
if(fileItem.isFormField()){
//isFormField()判断是否普通表单类型
}else {
String name = fileItem.getName();
fileItem.write(new File(path,name));
}
}
return "success";
}
开始以为是文件路径的问题
在项目里面一直找不到生成的路径
后来根据调试发现默认是上传到了tomcat下的webapp中
但是文件一直是空
发现问题原因:
解析出的request对象一直是空的
解决方法:
去掉在spring配置中的这段配置:
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="DefaultEncoding" value="UTF-8" />
<property name="MaxUploadSize" value="1048576" />
<property name="MaxInMemorySize" value="4096"/>
</bean>
然后发现文件就可以正常上传了