在SpringMvc中要使用文件的上传需要在springmvc.xml中配以下内容
<!-- 启用文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 限制上传文件的大小 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
//修改
@RequestMapping(value="/updateFood/{foodid}",method=RequestMethod.POST)
public String updateFood(@PathVariable String foodid,String foodName,String price,MultipartFile imageUrl,Model model) throws IllegalStateException, IOException{
String fileName=imageUrl.getOriginalFilename();
//如果文件不上传 代表不修改文件
if(fileName.equals("")){
service.updateFoodType1(foodid, foodName, price);
}else{
//文件存入的文件夹
String absPath="E:\\phg\\.metadata\\.me_tcat\\webapps\\SpringMvcCURD\\myImage";
//写入二进制的图片
imageUrl.transferTo(new File(absPath+"\\"+fileName));
service.updateFoodType(foodid, foodName, price,fileName);
}
return queryFood(null,null, model);
}
//新增
@RequestMapping(value="/addFood",method=RequestMethod.POST)
public String addFood(String foodName,String price,MultipartFile imageUrl,Model model) throws IllegalStateException, IOException{
//获取文件名
String fileName=imageUrl.getOriginalFilename();
//文件存入的文件夹
String absPath="E:\\phg\\.metadata\\.me_tcat\\webapps\\SpringMvcCURD\\myImage";
//写入定义好的文件夹
imageUrl.transferTo(new File(absPath+"\\"+fileName));
service.saveFood(foodName, price, fileName);
return queryFood(null,null, model);
}
//资源下载
@RequestMapping(value="/download",method=RequestMethod.GET)
public ResponseEntity<byte[]> download(String imagePath) throws IOException{
String absPath="E:\\phg\\.metadata\\.me_tcat\\webapps\\SpringMvcCURD\\myImage\\"+imagePath;
String fileName=imagePath;
//需要下载的目标文件
File file=new File(absPath);
//设置响应头
HttpHeaders hh=new HttpHeaders();
//设置下载的文件的名称
hh.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8"));
//读取目标文件为二进制数组
byte[] fileByte=FileCopyUtils.copyToByteArray(file);
//构建ResponseEntity对象
ResponseEntity<byte[]> re=new ResponseEntity<byte[]>(fileByte, hh, HttpStatus.CREATED);
return re;
}
<input type="file" name="imageUrl"/>