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

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • LabVIEW异步和同步通信详细分析及比较
  • 0基础学python-14:python进阶之面向对象
  • Linux指令ros学习python深度学习bug学习笔记
  • 景区客流统计系统提升服务精准度
  • 深入理解Session和Cookie的作用与联系
  • 《汇编语言 基于x86处理器》- 读书笔记 - Visual Studio 2019 配置 MASM环境
  • 产品经理-一份标准需求文档的8个模块(14)
  • 亚信安全发布2024年第24期《勒索家族和勒索事件监控报告》
  • LabVIEW比例压力控制阀自动测试系统
  • 前端学习常用技术栈
  • 物流EDI:马士基IFTMBF 订舱请求
  • js实现一键任意html元素生成截图功能
  • 洛阳建筑设计资质市场未来趋势
  • Web 中POST为什么会发送两次请求
  • Java反射和动态代理用法(附10道练习题)
  • 《剑指offer》分解让复杂问题更简单
  • 《用数据讲故事》作者Cole N. Knaflic:消除一切无效的图表
  • 10个最佳ES6特性 ES7与ES8的特性
  • Docker 1.12实践:Docker Service、Stack与分布式应用捆绑包
  • el-input获取焦点 input输入框为空时高亮 el-input值非法时
  • ES6--对象的扩展
  • Fastjson的基本使用方法大全
  • Javascript Math对象和Date对象常用方法详解
  • js 实现textarea输入字数提示
  • leetcode98. Validate Binary Search Tree
  • RxJS 实现摩斯密码(Morse) 【内附脑图】
  • Sequelize 中文文档 v4 - Getting started - 入门
  • Spring Cloud Feign的两种使用姿势
  • Sublime Text 2/3 绑定Eclipse快捷键
  • 基于游标的分页接口实现
  • 漫谈开发设计中的一些“原则”及“设计哲学”
  • 深入浅出Node.js
  • 使用阿里云发布分布式网站,开发时候应该注意什么?
  • 吐槽Javascript系列二:数组中的splice和slice方法
  • 【干货分享】dos命令大全
  • Java总结 - String - 这篇请使劲喷我
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • #ubuntu# #git# repository git config --global --add safe.directory
  • #每天一道面试题# 什么是MySQL的回表查询
  • (2009.11版)《网络管理员考试 考前冲刺预测卷及考点解析》复习重点
  • (6)STL算法之转换
  • (env: Windows,mp,1.06.2308310; lib: 3.2.4) uniapp微信小程序
  • (Ruby)Ubuntu12.04安装Rails环境
  • (二)windows配置JDK环境
  • (二)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (附源码)springboot教学评价 毕业设计 641310
  • (附源码)ssm高校志愿者服务系统 毕业设计 011648
  • (每日持续更新)信息系统项目管理(第四版)(高级项目管理)考试重点整理第3章 信息系统治理(一)
  • (删)Java线程同步实现一:synchronzied和wait()/notify()
  • (一)硬件制作--从零开始自制linux掌上电脑(F1C200S) <嵌入式项目>
  • (转载)深入super,看Python如何解决钻石继承难题
  • .NET Standard 的管理策略
  • .net 调用海康SDK以及常见的坑解释
  • .NET 通过系统影子账户实现权限维持
  • .php结尾的域名,【php】php正则截取url中域名后的内容