如果想上传文件,那么有两种方法可以解决。一种使用Spring框架中的东西。另外一种是使用原生的代码。
使用Spring框架非常简单。将如下xml放入到servlet.xml中。
1 2 3 4 5 6 7
| <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20000000" /> </bean>
|
然后在代码中这样写:
1 2 3 4 5 6 7 8 9 10 11
| @RequestMapping(value = "upload", method = RequestMethod.POST) public void upload(HttpServletRequest req, HttpServletResponse response, @RequestParam(value="file", required=true) MultipartFile file, ) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtils.copy(file.getInputStream(), bytes); byte[] byteArray = bytes.toByteArray();}
|
Html上传页面这样写:
1 2 3 4 5 6 7 8
| <form name="uploadForm" action="upload" method="POST" enctype="multipart/form-data" > <label>上传文件 </label><br/> <input type="file" name="file" size="100" style="width:300px;" /> <br /> <input type="submit" name="submit" value="submit"/> </form>
|
这样写完后,就可以上传一个不超过20M的文件了。
第二种方式不使用Spring框架。代码稍微复杂一些。HTML同上。但是没有那段XML内容。JAVA代码需要改为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| @RequestMapping(value = "upload", method = RequestMethod.POST) public void upload(HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException, FileUploadException, { boolean isMultipart = ServletFileUpload.isMultipartContent(req); HashMap<String, String> request = new HashMap<String, String>(); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 1024 * 20, null); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); upload.setSizeMax(1024 * 1024 * 20);
List<FileItem> fileItems = upload.parseRequest(req); Iterator<FileItem> iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString("UTF-8"); request.put(name, value); } else { byte[] filebytes = item.get(); if (StringUtils.isBlank(item.getName())) { continue; } request.put(item.getFieldName(), new String(filebyte, "utf-8")); } } } }
|
但是这两者不能同时使用,否则会有冲突。下一篇将介绍 如何解决两者之间的冲突 。