示例代码如下:
@Test
public void testFileName() throws IOException {
File file = new File("E:\\中文1.docx");
// 组装post请求体,以文件的形式发送
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 解决上传文件,文件名中文乱码问题
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 两种发送文件的方式
builder.addBinaryBody("file", file);
// builder.addPart("file", new FileBody(file));
HttpEntity reqEntity = builder.build();
// 创建post请求
HttpPost httpPost = new HttpPost("http://127.0.0.1:8500/upload");
// 设置请求体
httpPost.setEntity(reqEntity);
try (
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 发送请求并处理返回的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
) {
StatusLine statusLine = response.getStatusLine();
System.out.println("statusLine = " + statusLine);
}
}
核心代码为
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
这两句