当前位置: 首页 > news >正文

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")@ResponseBodypublic 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 {@Testpublic void testUpload() {// 本地文件上传到远程HttpClient.upload("E://Empty_P1.pdf", "http://localhost:9000/upload");}@Testpublic void testDownload() throws Exception {// 下载远程文件到本地String fileName = "Empty_P1.pdf";HttpClient.download("http://localhost:9000/download/" + fileName, "E://download/" + fileName);}
}
http://www.lryc.cn/news/401481.html

相关文章:

  • QT--控件篇四
  • opencv—常用函数学习_“干货“_2
  • 解析CSS与JavaScript的使用方法及ECMAScript语法规则
  • 从零开始学习嵌入式----结构体struct和union习题回顾
  • 建筑产业网元宇宙的探索与实践
  • 比较RMI、HTTP+JSON/XML、gRPC
  • 软件工程-可行性分析
  • iOS ------ 消息传递和消息转发
  • 计算机视觉之Vision Transformer图像分类
  • 【深度学习】BeautyGAN: 美妆,化妆,人脸美妆
  • RocketMQ~架构与工作流程了解
  • 学习Python的IDE功能--(一)入门导览
  • gdb调试多线程程序
  • 实战GraphRAG(一):初步体验GraphRAG及其与RAG的对比
  • 37、PHP 实现一个链表中包含环,请找出该链表的环的入口结点
  • LIMS系统对实验室管理有哪些帮助?
  • 在GPU上运行PyTorch
  • 【内网穿透】打洞笔记
  • 第59期|GPTSecurity周报
  • 算法2--贪心算法
  • 本地部署 EVE: Unveiling Encoder-Free Vision-Language Models
  • 阿里云CDN- https(设计支付宝春节开奖业务)
  • 为何众多卖家选择加入亚马逊VC平台?他们的决策依据是什么?
  • Windows与Linux双机热备软件推荐
  • Mysql基础与安装
  • 线程的死锁和并发安全
  • docker 启动提示can not create sys fs cgroup cpuset....问题处理
  • [C/C++入门][ifelse]19、制作一个简单计算器
  • API取数实战:企业微信API取数教程
  • AI算法18-最小角回归算法Least Angle Regression | LARS