依赖两个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.5.3</version>
</dependency>
java代码
/**
* 文件上传支持中文
*
* @param reportUrl
* @param filepath
* @param userId
* @param systemName
* @throws IOException
*/
public static void uploadReport(String reportUrl, String filepath,
String userId, String systemName) {
CloseableHttpClient closeableHttpClient = null;
CloseableHttpResponse response = null;
try {
closeableHttpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(reportUrl);
String filename = filepath.split("/")[filepath.split("/").length - 1];
File file = new File(filepath);
FileBody fileBody = new FileBody(file, ContentType.create("multipart/form-data", "UTF-8"), filename);
StringBody userIdStringBody = new StringBody(userId, ContentType.create("multipart/form-data", "UTF-8"));
StringBody systemNameStringBody = new StringBody(systemName, ContentType.create("multipart/form-data", "UTF-8"));
StringBody reportNameStringBody = new StringBody(filename, ContentType.create("multipart/form-data", "UTF-8"));
HttpEntity httpEntity = MultipartEntityBuilder
.create()
.setCharset(Charset.forName("UTF-8"))
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", fileBody)
.addPart("userId", userIdStringBody)
.addPart("systemName", systemNameStringBody)
.addPart("reportName", reportNameStringBody)
.build();
httpPost.setEntity(httpEntity);
response = closeableHttpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
System.out.println("上传成功");
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
StringBuffer buffer = new StringBuffer();
String str = "";
while ((str = reader.readLine()) != null && (str = reader.readLine()).trim().length() > 0) {
buffer.append(str);
}
System.out.println(buffer.toString());
System.out.println("上传失败:" + statusCode);
}
closeableHttpClient.close();
if (response != null) {
response.close();
}
} catch (Exception ex) {
System.out.println("uploadReport发生异常:" + ex);
} finally {
try {
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
if (response != null) {
response.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}