SpringBoot+HttpClient实现文件上传下载

服务端:SpringBoot

Controller

package com.liliwei.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class TestController {

    @RequestMapping("/upload")
    @ResponseBody
    public String testUpload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();

        file.transferTo(new File("E://upload/" + originalFilename));
        return "文件上传成功";
    }

    @RequestMapping("/download/{fileName:.+}")
    public ResponseEntity<byte[]> testDownload(HttpServletResponse response, @PathVariable("fileName") String fileName) {
        byte[] bytes = getFile("E://upload/" + fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return responseEntity;
    }

    public static byte[] getFile(String filePath) {
        File f = new File(filePath);
        FileInputStream fis = null;
        byte[] data = null;
        try {
            fis = new FileInputStream(f);
            data = new byte[fis.available()];
            fis.read(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                }
            }
        }
        return data;
    }
}

application.yml

server:
  port: 9000
  
# application.yml
spring:
  servlet:
    multipart:
      # 设置单个文件上传的最大值(比如50MB)
      max-file-size: 1000MB
      # 设置请求的最大总体大小(比如100MB)
      max-request-size: 1000MB

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.studio</groupId>
  <artifactId>SpringBootTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.7.18</version>
        </dependency>
          <dependency>
            <groupId>org.apache.httpcomponents.client5</groupId>
            <artifactId>httpclient5</artifactId>
            <version>5.3.1</version>
        </dependency>
  </dependencies>
  <build>
   <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
   </plugins>
  </build>
</project>

客户端:Apache HttpClient

代码

package com;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;

public class HttpClient {

    /**
     * 文件下载
     */
    public static void download(String targetUrl, String localFile) throws Exception {
        try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
            final HttpGet httpget = new HttpGet(targetUrl);

            System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());

            final byte[] result = httpclient.execute(httpget, response -> {
                System.out.println("----------------------------------------");
                System.out.println(httpget + "->" + new StatusLine(response));
                return EntityUtils.toByteArray(response.getEntity());
            });
            FileOutputStream fos = new FileOutputStream(new File(localFile));
            fos.write(result);
            fos.close();
        }
    }

    /**
     * 文件上传
     */
    public static void upload(String localFile, String targetUrl) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(targetUrl);
            FileBody fileBody = new FileBody(new File(localFile));
            HttpEntity httpEntity = MultipartEntityBuilder.create().addPart("file", fileBody).build();
            httpPost.setEntity(httpEntity);
            response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.err.println("服务器响应数据:" + EntityUtils.toString(resEntity));
            }
            EntityUtils.consume(resEntity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

测试

package com;

import org.junit.Test;

public class TestHttpClient {

    @Test
    public void testUpload() {
    	// 本地文件上传到远程
        HttpClient.upload("E://Empty_P1.pdf", "http://localhost:9000/upload");
    }

    @Test
    public void testDownload() throws Exception {
        // 下载远程文件到本地
        String fileName = "Empty_P1.pdf";
        HttpClient.download("http://localhost:9000/download/" + fileName, "E://download/" + fileName);
    }
}

相关推荐

  1. SpringBoot+HttpClient实现文件下载

    2024-07-17 19:18:02       23 阅读
  2. 文件下载

    2024-07-17 19:18:02       28 阅读
  3. springboot实现七牛云的文件下载

    2024-07-17 19:18:02       30 阅读
  4. SpringBoot 下载文件

    2024-07-17 19:18:02       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-17 19:18:02       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-17 19:18:02       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-17 19:18:02       62 阅读
  4. Python语言-面向对象

    2024-07-17 19:18:02       72 阅读

热门阅读

  1. 根据语义切分视频

    2024-07-17 19:18:02       19 阅读
  2. 量化交易对市场波动的反应机制

    2024-07-17 19:18:02       20 阅读
  3. Html_Css问答集(11)

    2024-07-17 19:18:02       19 阅读
  4. 最全—航班信息管理系统【数组版】

    2024-07-17 19:18:02       18 阅读
  5. 什么是HTTP协议攻击

    2024-07-17 19:18:02       20 阅读
  6. AnyConv OGG 转换器:轻松转换音频格式

    2024-07-17 19:18:02       24 阅读
  7. Local Cache(二)demo

    2024-07-17 19:18:02       20 阅读
  8. Git简要笔记

    2024-07-17 19:18:02       21 阅读
  9. 爬虫-存储数据

    2024-07-17 19:18:02       25 阅读
  10. Windows的包管理器Chocolatey

    2024-07-17 19:18:02       22 阅读