当前位置: 首页 > 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);}
}

相关文章:

SpringBoot+HttpClient实现文件上传下载

服务端&#xff1a;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.s…...

QT--控件篇四

一、对话框 在软件开发中&#xff0c;对话框&#xff08;Dialog&#xff09;是一种常见的用户界面元素&#xff0c;用于与用户进行交互和获取信息。它通常以模态或非模态的形式出现&#xff0c;模态对话框会阻止用户与应用程序的其他部分交互&#xff0c;直到对话框关闭为止&a…...

opencv—常用函数学习_“干货“_2

目录 五、矩阵计算函数 归一化矩阵 (normalize) 转置矩阵 (transpose) 求矩阵的逆 (invert) 翻转矩阵 (flip) 旋转矩阵 (rotate) 求矩阵的行列式 (determinant) 求矩阵的迹 (trace) 求矩阵的特征值和特征向量 (eigen) 六、代数运算 矩阵加法 (add) 矩阵减法 (subtra…...

解析CSS与JavaScript的使用方法及ECMAScript语法规则

一、CSS的三种使用方式 CSS&#xff08;层叠样式表&#xff09;用于定义网页的样式和布局。以下是CSS的三种使用方式&#xff1a; 1. 内联样式 内联样式是最直接的应用方式&#xff0c;它通过HTML标签的style属性来定义。 代码示例&#xff1a; <h1 style"color: …...

从零开始学习嵌入式----结构体struct和union习题回顾

一、通过结构体和自定义函数实现成绩从大到小的排序&#xff0c;要求在主函数内定义结构体数组。 #include <stdio.h> //定义一个结构体类型 typedef struct Student {int age;char name[32];float score; } STU; //定义一个函数实现成绩从小到大的排序 void fun(STU *p…...

建筑产业网元宇宙的探索与实践

在数字化浪潮的推动下&#xff0c;建筑产业网正迈入一个全新的元宇宙时代。这一变革不仅为建筑设计、施工与管理带来了革新&#xff0c;也为整个行业注入了新的活力与创造力。本文将深入探讨建筑产业网元宇宙的特点、应用及未来趋势&#xff0c;带您领略其在建筑行业中的独特魅…...

比较RMI、HTTP+JSON/XML、gRPC

RMI&#xff08;Remote Method Invocation&#xff0c;远程方法调用&#xff09;、HTTPJSON/XML、gRPC是三种不同的技术或协议&#xff0c;它们各自在远程通信、数据传输和服务交互方面有不同的特点和应用场景。以下是对这三种技术的详细比较&#xff1a; 1. RMI&#xff08;R…...

软件工程-可行性分析

一、可行性分析 可行性分析/研究目的是用最小的代价在尽可能短的时间内确定问题是否得到解决。 FVPV&#xff08;1r&#xff09;^n* FV&#xff1a;未来价值 PV&#xff1a;现值&#xff08;当前货币金额&#xff09; r&#xff1a;利率 n&#xff1a;时间期限 纯收入累计的现…...

iOS ------ 消息传递和消息转发

一&#xff0c;消息传递 在OC中&#xff0c;传递消息就是在对象上调用方法。 相对于C语言的方法就“静态绑定”的函数&#xff0c;在编译器就决定了运行时所要调用的函数。在OC中&#xff0c;如果向某对象传递消息&#xff0c;就会使用动态绑定机制来决定需要调用那个方法。调…...

计算机视觉之Vision Transformer图像分类

Vision Transformer&#xff08;ViT&#xff09;简介 自注意结构模型的发展&#xff0c;特别是Transformer模型的出现&#xff0c;极大推动了自然语言处理模型的发展。Transformers的计算效率和可扩展性使其能够训练具有超过100B参数的规模空前的模型。ViT是自然语言处理和计算…...

【深度学习】BeautyGAN: 美妆,化妆,人脸美妆

https://www.sysu-hcp.net/userfiles/files/2021/03/01/3327b564380f20c9.pdf 【深度学习】BeautyGAN: Instance-level Facial Makeup Transfer with Deep Generative Adversarial Network BeautyGAN: Instance-level Facial Makeup Transfer with Deep Generative Adversaria…...

RocketMQ~架构与工作流程了解

简介 RocketMQ 具有高性能、高可靠、高实时、分布式 的特点。它是一个采用 Java 语言开发的分布式的消息系统&#xff0c;由阿里巴巴团队开发&#xff0c;在 2016 年底贡献给 Apache&#xff0c;成为了 Apache 的一个顶级项目。 在阿里内部&#xff0c;RocketMQ 很好地服务了集…...

学习Python的IDE功能--(一)入门导览

项目视图是主要工具窗口之一。它包含项目目录、SDK 特定的外部库和临时文件。点击带条纹的按钮可以预览演示项目。您也可以按Alt1打开。点击以打开项目视图&#xff0c;展开项目目录以查看项目文件。双击以打开welcome.py。 切换到"学习"工具窗口继续学习本课次。…...

gdb调试多线程程序

目录 1、pstack查看各个线程的调用堆栈2、gdb调试多线程2.1 查看线程信息2.2 切换线程2.3 进入线程某层具体的调用堆栈2.4 调度器锁2.4.1 查看调度器锁模式 3、实战3.1 调试多线程崩溃3.2 调试多线程死锁 1、pstack查看各个线程的调用堆栈 命令&#xff1a; 1、查看进程id ps …...

实战GraphRAG(一):初步体验GraphRAG及其与RAG的对比

🌟实战GraphRAG(一):初步体验GraphRAG及其与RAG的对比 文章目录 🌟实战GraphRAG(一):初步体验GraphRAG及其与RAG的对比📖引言🔍一、GraphRAG与RAG的区别🚀二、GraphRAG使用示例1.安装GraphRAG2.运行索引器3.配置4.自动优化提示词5.运行索引管道6.使用查询引擎7…...

37、PHP 实现一个链表中包含环,请找出该链表的环的入口结点

题目&#xff1a; 题目描述 PHP 实现一个链表中包含环&#xff0c;请找出该链表的环的入口结点。 描述&#xff1a; 一个链表中包含环&#xff0c;请找出该链表的环的入口结点。 <?php /*class ListNode{var $val;var $next NULL;function __construct($x){$this->v…...

LIMS系统对实验室管理有哪些帮助?

LIMS系统对实验室管理提供了多方面的帮助&#xff0c;具体体现在以下几个方面&#xff1a; 1. 流程标准化与自动化 LIMS系统通过定义标准化的工作流程&#xff0c;如样品接收、测试分配、数据录入、结果审核和报告生成等&#xff0c;实现了实验室工作流程的自动化。这减少了人…...

在GPU上运行PyTorch

文章目录 1、查看GPU的CUDA版本2、下载CUDA版本3、安装cuDNN4、配置CUDA环境变量5、安装配置Anaconda6、使用Anaconda7、pycharm导入虚拟环境8、安装带GPU的PyTorch⭐9、总结 &#x1f343;作者介绍&#xff1a;双非本科大三网络工程专业在读&#xff0c;阿里云专家博主&#x…...

【内网穿透】打洞笔记

文章目录 前言原理阐述公网sshfrp转发服务 实现前提第一步&#xff1a;第二步第三步第四步 补充第五步&#xff08;希望隧道一直开着&#xff09;sftp传数据&#xff08;嫌云服务器上的网太慢&#xff09; 前言 租了一个云服务器&#xff0c;想用vscode的ssh远程连接&#xff…...

第59期|GPTSecurity周报

GPTSecurity是一个涵盖了前沿学术研究和实践经验分享的社区&#xff0c;集成了生成预训练Transformer&#xff08;GPT&#xff09;、人工智能生成内容&#xff08;AIGC&#xff09;以及大语言模型&#xff08;LLM&#xff09;等安全领域应用的知识。在这里&#xff0c;您可以找…...

376. Wiggle Subsequence

376. Wiggle Subsequence 代码 class Solution { public:int wiggleMaxLength(vector<int>& nums) {int n nums.size();int res 1;int prediff 0;int curdiff 0;for(int i 0;i < n-1;i){curdiff nums[i1] - nums[i];if( (prediff > 0 && curdif…...

论文解读:交大港大上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架(一)

宇树机器人多姿态起立控制强化学习框架论文解析 论文解读&#xff1a;交大&港大&上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架&#xff08;一&#xff09; 论文解读&#xff1a;交大&港大&上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化…...

Axios请求超时重发机制

Axios 超时重新请求实现方案 在 Axios 中实现超时重新请求可以通过以下几种方式&#xff1a; 1. 使用拦截器实现自动重试 import axios from axios;// 创建axios实例 const instance axios.create();// 设置超时时间 instance.defaults.timeout 5000;// 最大重试次数 cons…...

《基于Apache Flink的流处理》笔记

思维导图 1-3 章 4-7章 8-11 章 参考资料 源码&#xff1a; https://github.com/streaming-with-flink 博客 https://flink.apache.org/bloghttps://www.ververica.com/blog 聚会及会议 https://flink-forward.orghttps://www.meetup.com/topics/apache-flink https://n…...

【HTTP三个基础问题】

面试官您好&#xff01;HTTP是超文本传输协议&#xff0c;是互联网上客户端和服务器之间传输超文本数据&#xff08;比如文字、图片、音频、视频等&#xff09;的核心协议&#xff0c;当前互联网应用最广泛的版本是HTTP1.1&#xff0c;它基于经典的C/S模型&#xff0c;也就是客…...

大数据学习(132)-HIve数据分析

​​​​&#x1f34b;&#x1f34b;大数据学习&#x1f34b;&#x1f34b; &#x1f525;系列专栏&#xff1a; &#x1f451;哲学语录: 用力所能及&#xff0c;改变世界。 &#x1f496;如果觉得博主的文章还不错的话&#xff0c;请点赞&#x1f44d;收藏⭐️留言&#x1f4…...

push [特殊字符] present

push &#x1f19a; present 前言present和dismiss特点代码演示 push和pop特点代码演示 前言 在 iOS 开发中&#xff0c;push 和 present 是两种不同的视图控制器切换方式&#xff0c;它们有着显著的区别。 present和dismiss 特点 在当前控制器上方新建视图层级需要手动调用…...

【C++】纯虚函数类外可以写实现吗?

1. 答案 先说答案&#xff0c;可以。 2.代码测试 .h头文件 #include <iostream> #include <string>// 抽象基类 class AbstractBase { public:AbstractBase() default;virtual ~AbstractBase() default; // 默认析构函数public:virtual int PureVirtualFunct…...

DBLP数据库是什么?

DBLP&#xff08;Digital Bibliography & Library Project&#xff09;Computer Science Bibliography是全球著名的计算机科学出版物的开放书目数据库。DBLP所收录的期刊和会议论文质量较高&#xff0c;数据库文献更新速度很快&#xff0c;很好地反映了国际计算机科学学术研…...

【Veristand】Veristand环境安装教程-Linux RT / Windows

首先声明&#xff0c;此教程是针对Simulink编译模型并导入Veristand中编写的&#xff0c;同时需要注意的是老用户编译可能用的是Veristand Model Framework&#xff0c;那个是历史版本&#xff0c;且NI不会再维护&#xff0c;新版本编译支持为VeriStand Model Generation Suppo…...