http post访问文件上传接口,传递MultipartFile[]多文件和其他参数

导入包:

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>27.1-jre</version>
    </dependency>
    <!--        文件转MultipartFile-->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <!--        arrayutils -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.12.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.12</version>
    </dependency>
package com.example.demo.uploadFile;

import com.google.common.collect.Maps;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.*;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : 
 * @date :
 * @description :
 * @modifiedBy :
 */
public class FileUtil {
    /**
     * file转MultipartFile
     *
     * @param file 本地文件路径
     * @return
     */
    public static MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    private static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
    /**
     * 发送multipartFile
     *
     * @param url           请求路径
//     * @param file          MultipartFile流
//     * @param fileParamName controller对应的接收名称
     * @param headerParams  追加的请求头信息
     * @param otherParams   其他请求参数
     * @return
     */
    public static HttpResultDTO postMultipartFile(String url,
                                                  MultipartFile[] files,
                                                  Map<String, String> headerParams,
                                                  Map<String, String> otherParams) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {

            HttpPost httpPost = new HttpPost(url);
            //添加header
            if (headerParams != null) {
                for (Map.Entry<String, String> e : headerParams.entrySet()) {
                    httpPost.addHeader(e.getKey(), e.getValue());
                }
            }
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
            //加上此行代码解决返回中文乱码问题
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //文件流处理
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                builder.addBinaryBody("files", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            }

            if (otherParams != null) {

                for (Map.Entry<String, String> e : otherParams.entrySet()) {
                    //追加其他请求参数信息
                    builder.addTextBody(e.getKey(), e.getValue(), ContentType.create("text/plain", Consts.UTF_8));
                }
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            //执行提交
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            StatusLine statusLine = response.getStatusLine();
            int status = statusLine.getStatusCode();
            Header[] headers = response.getAllHeaders();
            String body = EntityUtils.toString(responseEntity);
            Map<String, String> headerMap = Maps.newHashMap();

            if (ArrayUtils.isNotEmpty(headers)) {
                for (Header header : headers) {
                    headerMap.put(header.getName(), header.getValue());
                }
            }
            HttpResultDTO httpResultDTO = new HttpResultDTO(status, body, headerMap);
            System.out.println(httpResultDTO);
            return httpResultDTO;

        } catch (Exception e) {
            //打印日志
            e.printStackTrace();
//            logger.error("postMultipartFile error,url:{},ex:{}", url, e.getMessage());
        }
        return null;
    }

    public static HttpResultDTO postFileWithParams(String url, String[] filesPath, String token, String params) {
        MultipartFile[] files = new MultipartFile[filesPath.length];

        for (int i = 0; i < filesPath.length; i++) {
            File file = new File(filesPath[i]);
            MultipartFile multipartFile = fileToMultipartFile(file);
            files[i] = multipartFile;
        }

        Map<String, String> headerParams = new HashMap<>();
        headerParams.put("token", token);
        Map<String, String> otherParams = new HashMap<>();
        otherParams.put("params", params);
        return postMultipartFile(url, files, headerParams, otherParams);
    }

    public static void main(String[] args) {
        String url = "http://localhost:8081/v1/file/upload";
        String token = "";
        String params = "";
        String[] filesPath = {"C:\\Users\\Admin\\Desktop\\7.6.txt","C:\\Users\\Admin\\Desktop\\7.6修.txt"};
        HttpResultDTO httpResultDTO = postFileWithParams(url, filesPath, token, params);
        System.out.println(httpResultDTO);
    }

}




package com.example.demo.uploadFile;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Map;

/**
 * @author : 
 * @date :
 * @description :
 * @modifiedBy :
 */
@Data
@AllArgsConstructor
public class HttpResultDTO {

    /**
     * 返回的状态码
     */
    private int status;

    /**
     * 返回的数据信息
     */
    private String body;

    /**
     * 返回的头信息
     */
    private Map<String, String> header;
}


  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值