Spring配置文件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="2000000"/> </bean>
jsp页面
<form:form commandName="product" action="product_save" method="post" enctype="multipart/form-data"> <fieldset> <legend>Add a product</legend> <p> <label for="name">Product Name: </label> <form:input id="name" path="name" cssErrorClass="error"/> <form:errors path="name" cssClass="error"/> </p> <p> <label for="description">Description: </label> <form:input id="description" path="description"/> </p> <p> <label for="price">Price: </label> <form:input id="price" path="price" cssErrorClass="error"/> </p> <p> <label for="image">Product Image: </label> <input type="file" name="images[0]"/> </p> <p id="buttons"> <input id="reset" type="reset" tabindex="4"> <input id="submit" type="submit" tabindex="5" value="Add Product"> </p> </fieldset> </form:form>
controller层,第一个方法是跳转到页面,第二个方法是提交表单的方法。这中做法,即使在表单页面中加入multiple在页面中可以选择多个文件,但是在后台接收的时候也只能接收一个,(我这边测试的结果是接收了多个文件中的最后一个)
@RequestMapping(value = "/product_input") public String inputProduct(Model model) { model.addAttribute("product", new Product()); return "ProductForm"; } @RequestMapping(value = "/product_save") public String saveProduct(HttpServletRequest servletRequest, @ModelAttribute Product product, BindingResult bindingResult, Model model) { List<MultipartFile> files = product.getImages(); List<String> fileNames = new ArrayList<String>(); if (null != files && files.size() > 0) { for (MultipartFile multipartFile : files) { String fileName = multipartFile.getOriginalFilename(); fileNames.add(fileName); File imageFile = new File(servletRequest.getServletContext() .getRealPath("/image"), fileName); try { multipartFile.transferTo(imageFile); } catch (IOException e) { e.printStackTrace(); } } } // save product here model.addAttribute("product", product); return "ProductDetails"; }
参考资料:spring MVC 学习指南
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/15400.html