翻译于 2013/03/05 20:01
在 Spring 3 里,是可以直接上传一个文件的。然后,对于如何在一个 jsp 文件里上传多个文件却几乎没有任何帮助文档。
要上传多个文件,这有三件基本的事情需要完成:
a) JSP 文件里必须有 input[file] 控件数组。
<td><input name="fileData[0]" id="image0" type="file" /></td> <td><input name="fileData[1]" id="image1" type="file" /></td>
b) Spring MVC 里的 ModelAttribute/Model 对象需要有一个 MultipartFile 列表。
import java.util.List; import org.springframework.web.multipart.commons.CommonsMultipartFile;
c) 在 dispatcher-servlet.xml[applicationContext-servlet.xml] 里配置 Multipart Resolver bean
<!-- Configure the multipart resolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean>
d) 在控制层里,从 Model 里读出文件并保存。
@RequestMapping(method = RequestMethod.POST) public String create(UploadItem uploadItem, BindingResult result, HttpServletRequest request, HttpServletResponse response, HttpSession session) { if (result.hasErrors()) { for (ObjectError error : result.getAllErrors()) { System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage()); } return "/uploadfile"; } // Some type of file processing... System.err.println("-------------------------------------------"); try { for(MultipartFile file:uploadItem.getFileData()){ String fileName = null; InputStream inputStream = null; OutputStream outputStream = null; if (file.getSize() > 0) { inputStream = file.getInputStream(); if (file.getSize() > 20000) { System.out.println("File Size exceeded:::" + file.getSize()); return "/uploadfile"; } System.out.println("size::" + file.getSize()); fileName = request.getRealPath("") + "/images/" + file.getOriginalFilename(); outputStream = new FileOutputStream(fileName); System.out.println("fileName:" + file.getOriginalFilename()); int readBytes = 0; byte[] buffer = new byte[10000]; while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) { outputStream.write(buffer, 0, readBytes); } outputStream.close(); inputStream.close(); // .......................................... session.setAttribute("uploadFile", file.getOriginalFilename()); } //MultipartFile file = uploadItem.getFileData(); } } catch (Exception e) { e.printStackTrace(); } return "redirect:/forms/uploadfileindex"; }
我已经在 @ RoseIndia 这里介绍了如何在控制层中动态建立文件节点并提交和保存。
可以直接下载源码并根据需要替换掉下面 JSP 文件中:
Upload.jsp
<%@page contentType="text/html;charset=UTF-8"%> <%@page pageEncoding="UTF-8"%> <%@ page session="false"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <html> <head> <META http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Upload Example</title> <script language="JavaScript"> var count=0; function add(type) { //Create an input type dynamically. var table = document.getElementById("fileUploadTable"); var tr = document.createElement("tr"); var td = document.createElement("td"); var element = document.createElement("input"); //Assign different attributes to the element. element.setAttribute("type", "file"); element.setAttribute("value", ""); element.setAttribute("name", "fileData["+type+"]"); //Append the element in page (in span). td.appendChild(element); tr.appendChild(td); table.appendChild(tr); } function Validate() { var image =document.getElementById("image").value; if(image!=''){ var checkimg = image.toLowerCase(); if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.jpeg|\.JPEG)$/)){ alert("Please enter Image File Extensions .jpg,.png,.jpeg"); document.getElementById("image").focus(); return false; } } return true; } </script> </head> <body> <form:form modelAttribute="uploadItem" name="frm" method="post" enctype="multipart/form-data" onSubmit="return Validate();"> <fieldset><legend>Upload File</legend> <table > <tr> <input type="button" name="Add Image" onclick="add(count++)" value="Add Image"/> </tr> <tr> <table id="fileUploadTable"> <!--td><form:label for="fileData" path="fileData">File</form:label><br /> </td> <td><input name="fileData[0]" id="image0" type="file" /></td> <td><input name="fileData[1]" id="image1" type="file" /></td--> </table> </tr> <tr> <td><br /> </td> <td><input type="submit" value="Upload" /></td> </tr> </table> </fieldset> </form:form> </body> </html>
UploadItem.java, 为私有变量 private List fileData 生成 getter 和 setter 方法, UploadFileController.java,然后复制和粘贴上文提到的create(…) 。
注意:如果在 Spring MVC 中上传文件有问题的话,请添加一个 MultipartFilter。查看这里.
<filter> <filter-name>multipartFilter</filter-name> <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class> </filter> <filter-mapping> <filter-name>multipartFilter</filter-name> <url-pattern>/springrest/*</url-pattern> </filter-mapping>
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>10000000</value> </property> </bean>
评论删除后,数据将无法恢复
评论(4)
提交的时候总是提示:
java.io.FileNotFoundException: d:\temp\e81b35ca-6c25-47b5-8da5-232ef83b2d65.mmap
神马情况?