1:前台
注意点:1.必须是post请求。
2:要加上 enctype="multipart/form-data"
2:后台
@RequestMapping("/updateitem")
public String updateitem(Items items , MultipartFile pictureFile) throws IOException {
// 获得上传源文件的名字和格式
String filename = pictureFile.getOriginalFilename();
//创建一个名字和原文件一样格式,名字不一样
String newName = UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
//设置文件保存的路径
String path="F:/"+newName;
File file1 = new File(path);
//把原文件按照新的file写到磁盘
pictureFile.transferTo(file1);
items.setPic(newName);
try {
itemService.updateitem(items);
return "success";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
3:配置文件
在springMvc.xml中设置文件解析器。注意id必须写并且值是固定的
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
maven中要加入上传文件的依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>