1.在springmvc.xml中配置文件解析器(别忘了在form中加上enctype="multipart/form-data"):
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值,设置为5MB -->
<property name="maxUploadSize" value="5242880" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
2.在action中定义文件上传的方法:
public String editItemsSubmit(MultipartFile items_pic,HttpServletRequest request) throws Exception{
String originalFilename = items_pic.getOriginalFilename();
//上传图片
if(items_pic!=null && originalFilename!=null && originalFilename.length()>0){
//存储图片的物理路径
String pic_path = request.getServletContext().getRealPath("/upload");
//新的图片名称
String newFileName = UUID.randomUUID() + originalFilename.split(".")[originalFilename.split(".").length-1];
//新图片
File newFile = new File(pic_path+"//"+newFileName);
//将内存中的数据写入磁盘
items_pic.transferTo(newFile);
}
}
这样就可以实现springmvc的文件上传了(当然别忘了引入jar包)