您的位置:首页 > 编程语言 > Java开发

JAVA Server上传文件 Spring MultipartResolver 或者 ServletFileUpload

2017-12-28 11:16 471 查看
转载自http://blog.csdn.net/cctt_1/article/details/8800964
如果想上传文件,那么有两种方法可以解决。一种使用Spring框架中的东西。另外一种是使用原生的代码。
使用Spring框架非常简单。将如下xml放入到servlet.xml中。

[html] view plain copy print?<bean id=“multipartResolver”
class=“org.springframework.web.multipart.commons.CommonsMultipartResolver”>
<property name=“maxUploadSize”
value=“20000000” />
<!– 上传限制 20M –>

然后在代码中这样写:

[java] view plain copy print?@RequestMapping(value = “upload”, method = RequestMethod.POST)
public void upload(HttpServletRequest req, HttpServletResponse response,
@RequestParam(value=“file”, required=true) MultipartFile file,
)
&nb
4000
sp; throws IOException {
// 1. upload file, 获取bytes内容

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
IOUtils.copy(file.getInputStream(), bytes);
byte[] byteArray = bytes.toByteArray();}
@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上传页面这样写:[html] view plain copy print?<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代码需要改为:

[java] view plain copy print?@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”));
}
}
}
}

但是这两者不能同时使用,否则会有冲突。下一篇将介绍如何解决两者之间的冲突
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐