SpringBoot+HttpClient实现文件上传下载

服务端:SpringBoot

Controller

package com.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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值