目录
正文
本文讲解多文件上传方法,不比较上传有几种方法和效率,而是定向分析apache的httpmime包的MultipartEntityBuilder类,源码包:httpmime-4.5.2.jar
一、常用用法
1.上传文件
三个传值方法,addPart、addBinaryBody、addTextBody如下图:
1 MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); 2 entityBuilder.addBinaryBody("file",new byte[]{},ContentType.DEFAULT_BINARY,"file.jpg"); 3 entityBuilder.addPart("owner","111"); 4 entityBuilder.addTextBody("paramter1", "aaa");
2.接收文件
1 //将当前上下文初始化给 CommonsMutipartResolver (多部分解析器) 2 CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext()); 3 //判断是否多文件上传 4 if(multipartResolver.isMultipart(request)){ 5 //将request变成多部分request 6 MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request; 7 Map<String,Object> map=multiRequest.getParameterMap(); 8 //获取multiRequest 中所有的文件名 9 Iterator<String> iter=multiRequest.getFileNames(); 10 //遍历所有文件 11 while(iter.hasNext()){ 12 MultipartFile file=multiRequest.getFile(iter.next().toString()); 13 //to do 14 } 15 }
二、注意点
注意点1,使用addBinaryBody的坑
首先看看源码:
MultipartEntityBuilder 的 addBinaryBody 有6种不同用法,一般都是上传File即可。着重看下图2个红色名字的方法。
源码如下:
1 public MultipartEntityBuilder addBinaryBody( 2 final String name, final byte[] b, final ContentType contentType, final String filename) { 3 return addPart(name, new ByteArrayBody(b, contentType, filename)); 4 } 5 6 public MultipartEntityBuilder addBinaryBody( 7 final String name, final byte[] b) { 8 return addBinaryBody(name, b, ContentType.DEFAULT_BINARY, null); 9 } 10 11 public MultipartEntityBuilder addBinaryBody( 12 final String name, final File file, final ContentType contentType, final String filename) { 13 return addPart(name, new FileBody(file, contentType, filename)); 14 } 15 16 public MultipartEntityBuilder addBinaryBody( 17 final String name, final File file) { 18 return addBinaryBody(name, file, ContentType.DEFAULT_BINARY, file != null ? file.getName() : null); 19 } 20 21 public MultipartEntityBuilder addBinaryBody( 22 final String name, final InputStream stream, final ContentType contentType, 23 final String filename) { 24 return addPart(name, new InputStreamBody(stream, contentType, filename)); 25 } 26 27 public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream) { 28 return addBinaryBody(name, stream, ContentType.DEFAULT_BINARY, null); 29 }
如上图:需要特别注意 传byte[]字节数组时,必须使用4参传值,且第四参必须带后缀名:
entityBuilder.addBinaryBody("file",new byte[]{},ContentType.DEFAULT_BINARY,"fileName.jpg");
如果使用上图中两参的,最后fileName不传,默认为null,会导致接收文件时multiRequest.getFileNames()(见1.2接收方法代码)为空!就会获取不到文件!
注意点2 isMultipart:
multipartResolver.isMultipart(request),这里判断是否为多文件上传,要求
1.方法为POST。
2.contentType以"mutipart/"开头。源码追踪如下: