如果想上传文件,那么有两种方法可以解决。一种使用Spring框架中的东西。另外一种是使用原生的代码。
使用Spring框架非常简单。将如下xml放入到servlet.xml中。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20000000" /> <!-- 上传限制 20M --> </bean>
然后在代码中这样写:
@RequestMapping(value = "upload", method = RequestMethod.POST) public void upload(HttpServletRequest req, HttpServletResponse response, @RequestParam(value="file", required=true) MultipartFile file, ) throws IOException {
// 1. upload file, 获取bytes内容 ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtils.copy(file.getInputStream(), bytes);byte[] byteArray = bytes.toByteArray();
}
Html上传页面这样写:
<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代码需要改为:
@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")); } } } }
但是这两者不能同时使用,否则会有冲突。下一篇将介绍如何解决两者之间的冲突。