您的位置:首页 > 编程语言 > Java开发

java 文件上传demo

2017-08-23 15:40 309 查看
每次写代码都要查找,所以就放这里面备份了

基本pom引用:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>


以下是实现方法:

public static String doPost(String url, Map<String, String> paramMap, String filePath, String fileName){
if (StringUtils.isEmpty(url) || StringUtils.isEmpty(filePath) ) {
throw new IllegalArgumentException("Params error!");
}

HttpPost httpPost = new HttpPost(url);
CloseableHttpClient httpClient = HttpClients.createDefault();

try {

MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.setCharset(Consts.UTF_8);
FileBody fileBody;

File file = new File(filePath);
if (StringUtils.isNotEmpty(fileName)) {
fileBody = new FileBody(file, ContentType.DEFAULT_BINARY, fileName);
} else {
fileBody = new FileBody(file);
}

builder.addPart("file", fileBody);

if (MapUtils.isNotEmpty(paramMap)) {
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
builder.addPart(entry.getKey()
, new StringBody(entry.getValue()
, ContentType.create("text/plain", Consts.UTF_8)));
}
}

String result;
httpPost.setEntity(builder.build());
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("Unexpected failure: " + statusLine.toString());
}

HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
EntityUtils.consume(resEntity);
} else {
result = null;
}
} finally {
response.close();
}

return result;
} catch (Exception e) {
throw new RuntimeException("Exception occurred when send post request[url:" + url, e);
} finally {
try {
httpClient.close();
} catch (Exception e) {
//np
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 备份