使用MultipartEntityBuilder实现文件上传

使用MultipartEntityBuilder实现文件上传

参考:【1

原理
  1. 从httpclient 4.3开始,使用MultipartEntityBuilder实现文件上传
  2. 文件或者文件流可以封装成ContentBody,进而被封装到MultipartEntityBuilder中,再创建出multipartEntity,作为HTTP请求的HttpEntity,最终被发送到服务端。整个对象封装流程如下:File/Stream>>ContentBody>>MultipartEntityBuilder>>multipartEntity>>HttpEntity
准备工作
  1. 引入httpclient依赖

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.8</version>
    </dependency>
    
使用addPart+File方法上传

使用addPart(String name, ContentBody contentBody)方法完成上传,其中ContentBody的实现类是FileBody。支持一次传多个文件。

HttpPost uploadPost = new HttpPost(uri);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart(TENANT_ID, new StringBody(tenantId, ContentType.TEXT_PLAIN))
       .addPart("path", new StringBody(path, ContentType.TEXT_PLAIN));
for (int i = 0; i < files.length; i++) {
    FileBody fileBody = new FileBody(files[i]);
    builder.addPart("file", fileBody);
}
HttpEntity multipartEntity = builder.build();
uploadPost.setEntity(multipartEntity);
CloseableHttpResponse response = httpClient.execute(uploadPost)
使用addPart+Stream方法上传

使用addPart(String name, ContentBody contentBody)方法完成上传,其中ContentBody的实现类是InputStreamBody。支持一次传多个文件。

HttpPost uploadPost = new HttpPost(uri);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart(TENANT_ID, new StringBody(tenantId, ContentType.TEXT_PLAIN))
       .addPart("path", new StringBody(path, ContentType.TEXT_PLAIN));
for (int i = 0; i < files.length; i++) {
	InputStreamBody inputStreamBody = new InputStreamBody(inputs[i], ContentType.APPLICATION_OCTET_STREAM, fileNames[i]);
	builder.addPart("file", inputStreamBody);
}
HttpEntity multipartEntity = builder.build();
uploadPost.setEntity(multipartEntity);
CloseableHttpResponse response = httpClient.execute(uploadPost)
使用addBinaryBody上传

使用addBinaryBody(String name, InputStream stream, ContentType contentType, String filename)方法

HttpPost uploadPost = new HttpPost(uri);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart(TENANT_ID, new StringBody(tenantId, ContentType.TEXT_PLAIN))
       .addPart("path", new StringBody(path, ContentType.TEXT_PLAIN))
       .addBinaryBody("file", input, ContentType.APPLICATION_OCTET_STREAM, fileName);
HttpEntity multipartEntity = builder.build();
uploadPost.setEntity(multipartEntity);
CloseableHttpResponse response = httpClient.execute(uploadPost)
  • 4
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值