前台:
1.表单提交方式为post
2.有文件上传输入框<input type="file" name="xxx"这里的name是什么,后台接收的MutipartFile xxx ,名称一致
3.form表单中不许添加entype="mutipart/form-data"
后台
1.导jar包
commons-io.jar
commons-fileupload.jar
2.配置文件上传解析器 ( id 必须为mutipartResolver)
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"/>
</bean>
3.用MutipartFile接收参数,参数名称和input中的name值一致
以下是文件的上传和修改
@RequestMapping("/addProduct.do") public String addProduct(Product product, MultipartFile file, HttpSession session) throws IOException { // System.out.println(product.getName()); String path=session.getServletContext().getRealPath("/productImg"); File file1=new File(path); if(!file1.exists()){ file1.mkdirs(); } String fileName=System.currentTimeMillis()+"-"+file.getOriginalFilename(); System.out.println(fileName); file.transferTo(new File(path+File.separator+fileName)); product.setId(IdUtils.getUUID()); product.setImgurl("/productImg/"+fileName); adminService.addProduct(product); return "/admin/listProduct.do"; }
@RequestMapping("/editProduct.do") public String editProduct(Product product,HttpSession session,MultipartFile file) throws IOException { System.out.println(file.getOriginalFilename()); if(!file.isEmpty()){ String path=session.getServletContext().getRealPath("/productImg"); //String path="D:/idea-workspace/bookStore/src/main/webapp/productImg"; Product product1=productService.findProductById(product.getId()); File file1=new File(path,file.getOriginalFilename()); if(file1.exists()){ file1.delete(); } String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename(); product.setImgurl("/productImg/"+fileName); System.out.println(fileName); file.transferTo(new File(path,fileName)); } adminService.editProduct(product); return "/admin/listProduct.do"; }
原文:https://www.cnblogs.com/liuna369-4369/p/10930731.html