标签:spring mvc java 文件上传
Spring3.0+Apache Tomcatv7.0+JDK1.7.0_u45+J2EE1.4验证通过。
需求:使用JSP页面上传文件时,同时需要传递相关参数。
1、 需要将form设置为enctype="multipart/form-data"method="post"参数;
2、 由于此时URL参数不能通过request.getParameter()获得,所以为了让@RequestMapping中设置的params="command=upload"条件生效,需要将参数直接加到表单的action中action="item.do?command=upload";
3、 在控制器处理时,使用item.isFormField(),item.getFieldName();item.getString()等方法去获取表单域属性名和参数;
JAVA类 import org.apache.commons.fileupload.DiskFileUpload; import org.apache.commons.fileupload.FileItem;
@RequestMapping(value = "item", params = "command=upload", method = RequestMethod.POST) public String upload(ItemActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fullFileName = null; //Get real absolute path String realPath = request.getSession().getServletContext() .getRealPath("/images"); System.out.println("realPath=" + realPath);
DiskFileUpload disk = new DiskFileUpload(); try { List<FileItem> files = (List<FileItem>) disk.parseRequest(request); for (FileItem item : files) { // Parse the parameter if (item.isFormField()) { System.out.println("item.isFormField()"); String field = item.getFieldName(); if (field != null) { if (field.equalsIgnoreCase("itemNo")) { itemNo = item.getString(); System.out.println("itemNo=" + itemNo); } }
}
// parse the file data fullFileName = item.getName(); if (fullFileName == null) { System.out.println("fullFileName not existed."); continue; } //Retrive the filename from full pathname. String fileName1 = fullFileName.substring(fullFileName .lastIndexOf("\\") + 1); File file1 = new File(realPath, fileName1); file1.getParentFile().mkdirs(); file1.createNewFile();
InputStream ins = item.getInputStream(); OutputStream ous = new FileOutputStream(file1);
try { byte[] buffer = new byte[1024]; int len = 0; while ((len = ins.read(buffer)) > -1) ous.write(buffer, 0, len);
} finally { ous.close(); ins.close(); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
return "redirect:item.do"; }
|
JSP页面: <form name="itemForm" id="itemForm" action="item.do?command=upload" enctype="multipart/form-data" method="post"> <input type="hidden" name="itemNo" value="${item.itemNo }"> <input name="itemFile" type="file" class="text1" size="40" maxlength="40">(必须是.gif或.jpg文件) |
JSP页面/Apache FileUpload组件上传文件的同时,传递其他参数的方法
标签:spring mvc java 文件上传
原文地址:http://blog.csdn.net/zxygww/article/details/45740693