1.该配置的都配置好了
①springmvc.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20971500"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>
</bean>
②form表单
enctype=“multipart/form-data”
③输入框
<input type="file" name="pic"/>
**注意:**不能和实体类的名字一样,比如我的实体类名:
private String newsPic;
④controller
controller方法中,参数加上如下:
@RequestParam MultipartFile pic
⑤最后一步:
//获取原始文件名称
String originalFileName = pic.getOriginalFilename();
if (pic!=null&&originalFileName!=null&&originalFileName.length()>0) {
//得到图片上传的位置
String path = request.getSession().getServletContext().getRealPath("/pic/");
//判断该路径是否存在,不存在就创建
File newFile = new File(path);
if (!newFile.exists()) {
newFile.mkdir();
}
//图片新名字,唯一值
String newPicName = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf("."));
//创建新文件并上传
pic.transferTo(new File(path, newPicName));
news.setNewsPic(newPicName);
}