java 文件上传demo
2017-08-23 15:40
309 查看
每次写代码都要查找,所以就放这里面备份了
基本pom引用:
以下是实现方法:
基本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 上传文件到七牛云存储的demo
- Java调用uploadify实现文件上传Demo实现
- Java调用uploadify实现文件上传Demo实现
- 安卓Android文件上传Demo报错 java.io.FileNotFoundException: /external/images/media/16: open failed: ENOENT (N
- java上传文件到hdfs简单demo
- Socket+JDBC+IO实现Java文件上传下载器DEMO详解
- java struts2结合swfupload实现上传文件的demo教程
- Java上传文件进度条的实现方法(附demo源码下载)
- 【javaweb】form表单的文件上传demo
- java 文件或图片的上传小demo
- Java(Servlet)上传文件的小demo
- java实现文件上传的简单demo
- Java调用uploadify实现文件上传Demo实现
- java文件上传Demo(必看篇)
- 【Java】上传文件进度条的实现方法(附demo源码下载)
- java操作hadoop hdfs,实现文件上传下载demo
- AFNetworking 3.0携带参数上传文件Demo 付java服务器端代码
- java IO流实现文件上传的demo
- java上传本地文件到HDFS简单demo
- Java网络编程Demo(二)TCP文件上传