Analysis of multi part types in spring MVC
On the modify goods page, add the upload goods picture function.
When submitting the data of enctype = "multipart / form data" in the page form, spring MVC needs to parse the data of multipart type.
Configure the multipart type parser in springmvc.xml.
<!-- File upload --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- Set the maximum size of the uploaded file to 5 MB --> <property name="maxUploadSize"> <value>5242880</value> </property> </bean>
Add the jar for uploading pictures
Add dependency
<!-- File upload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
Dependency tree
[INFO] \- commons-fileupload:commons-fileupload:jar:1.3.1:compile [INFO] \- commons-io:commons-io:jar:2.2:compile
As you can see, it also indirectly depends on Commons IO: commons IO: jar
Upload picture code
- page
<tr> <td>Commodity pictures</td> <td> <c:if test="${items.pic !=null}"> <img src="/pic/${items.pic}" width=100 height=100/> <br/> </c:if> <input type="file" name="items_pic"/> </td> </tr>
- controller method
Modify: product modify controller method:
@RequestMapping("/editItemsSubmit") public String editItemsSubmit(ItemsCustom itemsCustom, MultipartFile items_pic) throws Exception { //Original name String originalFilename = items_pic.getOriginalFilename(); //Upload pictures if (items_pic != null && originalFilename != null && originalFilename.length() > 0) { //Physical path to store pictures String pic_path = "D:\\tmp\\"; //New picture name String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")); //New picture File newFile = new File(pic_path + newFileName); //Write data in memory to disk items_pic.transferTo(newFile); //Write the new picture name to itemsCustom itemsCustom.setPic(newFileName); } }