java 文件上传demo

每次写代码都要查找,所以就放这里面备份了

基本pom引用:

        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpclientartifactId>
            <version>4.5.2version>
        dependency>
        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpmimeartifactId>
            <version>4.5.2version>
        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
            }
        }
    }

你可能感兴趣的:(随记,web,java)