Springmvc Study Notes (17)-upload images
Springmvc Study Notes (17)-upload images
This article shows how to upload images in springmvc
Analysis of Multiple part types in springmvc
On the modify product page, add the upload product image function.
Submit in formenctype="multipart/form-data"Springmvc needs to parse multipart data.
Configure the multipart parser in springmvc. xml.
5242880
Add the jar to upload the image
Add dependency
Commons-fileupload
Commons-fileupload
1.3.1
Dependency tree
[INFO] \- commons-fileupload:commons-fileupload:jar:1.3.1:compile[INFO] \- commons-io:commons-io:jar:2.2:compile
We can see that it is indirectly dependent.commons-io:commons-io:jar
Create a virtual directory for storing images
You can also directly modify tomcat configuration and add a virtual directory in the conf/server. xml file.
Note: In the image virtual directory, you must grade the image directory (to improve I/o performance). Generally, we create images by date (year, month, or day.
Upload Image Code Page
<Code class = "language-jsp hljs xml"> product image <c: if test = "$ {items. pic! = Null} "> </c: if> <input type = "file" data-cke-saved-name = "items_pic" name = "items_pic" data-cke-editable = "1" contenteditable = "false"> </code>Controller Method
Modify: Product controller modification method:
@RequestMapping("/editItemsSubmit") public String editItemsSubmit( Model model, HttpServletRequest request, Integer id, @ModelAttribute("items") @Validated(value = ValidGroup1.class)ItemsCustom itemsCustom, BindingResult bindingResult, MultipartFile items_pic )throws Exception {
// Original Name String originalFilename = items_pic.getOriginalFilename (); // upload the image if (items_pic! = Null & originalFilename! = Null & originalFilename. length ()> 0) {// the physical path for storing the image String pic_path = "D: \ tmp \"; // The new image name String newFileName = UUID. randomUUID () + originalFilename. substring (originalFilename. lastIndexOf (". "); // new Image File newFile = new File (pic_path + newFileName); // write data in memory to the disk items_pic.transferTo (newFile ); // write the new image name to itemsCustom. setPic (newFileName );}