>最近正好遇到这个需求,在我们网站上传的图片、视频等需要通过接口上传到crm那边,记录一下,以后再遇到可以当作一个工具类使用。
需要引用的依赖:
httpclient-4.5.3.jar,httpmime-4.3.jar
```
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3</version>
</dependency>
```
代码如下:
```Java
public String uploadFile(String url, MultipartFile multipartFile) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
String responseStr;
try {
logger.info("this file ContentType:" + multipartFile.getContentType());
//builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getOriginalFilename());
builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.create(multipartFile.getContentType()), multipartFile.getOriginalFilename());
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// builder.setMode(HttpMultipartMode.RFC6532);
builder.setCharset(Charset.forName("UTF-8"));
HttpEntity multipart = builder.build();
post.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity responseEntity = response.getEntity();
responseStr= EntityUtils.toString(responseEntity, "UTF-8");
logger.info("requestUrl is {}, response is {}", url, responseStr);
} catch (Exception e) {
return null;
}
return responseStr;
}
```
**2021-6-10 更新**
今天发现可以这么弄,发送的时候设置 ContentType,不然像之前一直发送的都是 MULTIPART_FORM_DATA 类型,
通过 `ContentType.create(multipartFile.getContentType())` 可以获取到文件本身的 ContentType,我今天看源码才发现的。。。。
所以说看源码是多么多么的重要啊!!! ———.———
具体修改的代码如下:(上面也更新了~)
```
builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.create(multipartFile.getContentType()), multipartFile.getOriginalFilename());
```
**2021-6-24 更新**
真是坎坷曲折啊,又发现一个上传文件的坑。
今天发现上传中文名称的文件时,返回的文件名会乱码。
>https://blog.csdn.net/youshounianhua123/article/details/81100778
HttpClient上传文件时,会调用doWriteTo方法,写一个输出流,但是在调用formatMultipartHeader方法时,底层主要有3种不同的实现,3种方式的采用的字符集不一样。
解决方案是:
```
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
```
或者
```
builder.setMode(HttpMultipartMode.RFC6532);
```
以上代码已经更新。
没想到一个工具类隐藏的坑也这么多。。。。。。

-4d90cecae28f46a8be82131ed3f4d910.png)
使用HttpClient通过Post请求发送MultipartFile文件