SpringBoot接收MultipartFile对象,不下载到本地,进行文件传输。

一. 概述

    当我们从前端接收到文件,需要调用其他服务的接口转发这些文件时,大多数人会选择先下载到本地,然后再删除。这篇文章就介绍如何通过Apache  HttpClient进行文件传输。从前端接收到文件后,无需下载到本地,直接进行转发。

二. Apache  HttpClient 介绍

  Apache HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包。它支持HTTP协议最新的版本和建议,并且广泛应用于各种Java项目中,包括Apache Jakarta上的其他著名开源项目如Cactus和HTMLUnit。这里就不再继续赘述,有兴趣的可以专门去了解一下。

三.具体实现

       1. 首先就是引入依赖

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

        2.具体代码实现

private void submitAttachment(MultipartFile[] attachment) throws Exception {
    //这里配置其他的表单参数,根据具体的接口而定
    Map<String, Object> attachmentParam = new HashMap<>();
    attachmentParam.put("filename", "GISERRORREPORT");
    //这里是需要转发文件的url
    String attPath = "www.baidu.com";
    CloseableHttpClient httpClient = HttpClients.createDefault();
    JSONObject jsonResult = null;
    // 创建HttpPost实例
    HttpPost httpPost = new HttpPost(attPath);
    // 请求参数配置,设置超时信息
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
            .setConnectionRequestTimeout(60000).build();
    httpPost.setConfig(requestConfig);
    try {
       //用于构建HTTP POST请求的多部分实体(multipart/form-data)
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        //拓展多文件传输,单文件同理
        for (MultipartFile file : attachment) {
            String fileName = file.getOriginalFilename();
            // 添加文件流,"file"为实际表单参数的key
            builder.addBinaryBody("file", file.getInputStream(), ContentType.create(file.getContentType()), fileName);
        }
        //将其他表单参数加入builder当中
        for (Map.Entry<String, Object> entry : attachmentParam.entrySet()) {
            builder.addPart(entry.getKey(), new StringBody((String) entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
        }

        //构建HttpPost实例的实体部分
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        // 执行提交
        HttpResponse response = httpClient.execute(httpPost);
        //获取接口返回code
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 将返回结果转化成res和json对象
            String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            jsonResult = JSONObject.parseObject(res);
            log.info("res:{}", res);
        }
    } catch (Exception e) {
        e.printStackTrace();
        log.error("调用HttpPost失败!" + e.getMessage());
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                log.error("关闭HttpPost连接失败!");
            }
        }
    }

}

因为 Apache  HttpClient 的特性,所以代码行数较多,因为它可以更加精确的定制Http请求,这里的Json使用的是FastJson。

如果解决了您的问题,麻烦一键三连吧!

  • 14
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 提供了强大的功能来处理MultipartFile,这是一种在HTTP请求中上传的文件类型。当你需要解析XLS文件时,通常会涉及到读取Excel内容并将其转换成可操作的数据结构。以下是一个简单的步骤来解析`.xls`文件: 1. 引入依赖:首先在你的Spring Boot项目中添加Apache POI库,它是Java处理Microsoft Office文件(包括.xls)的流行库。可以在pom.xml或build.gradle文件中添加依赖: ```xml <!-- Maven --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.0.0</version> <!-- 或者最新版本 --> </dependency> <!-- Gradle --> implementation 'org.apache.poi:poi-ooxml:5.0.0' <!-- 或者最新版本 --> ``` 2. 处理上传:当用户上传文件时,在Controller层接收并处理MultipartFile: ```java @PostMapping("/upload") public String handleExcelUpload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "File is empty"; } try { // 将MultipartFile转换为InputStream InputStream inputStream = file.getInputStream(); // 创建一个FileCopyHelper实例来读取Excel内容 FileCopyHelper copyHelper = new FileCopyHelper(new File("temp.xlsx")); // 将InputStream写入临时文件 copyHelper.copyTo(inputStream, new FileOutputStream("temp.xlsx")); // 使用HSSFWorkbook读取文件 Workbook workbook = new HSSFWorkbook(new FileInputStream("temp.xlsx")); // 打开第一个sheet进行处理 Sheet sheet = workbook.getSheetAt(0); // ...解析Excel内容... // 关闭资源 workbook.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); return "Error while processing file"; } return "File uploaded successfully"; } ``` 3. 解析数据:使用POI库提供的类如`Row`和`Cell`来逐行读取和处理Excel中的数据。例如,你可以遍历每一行,获取单元格值,并根据需要处理这些数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值