HttpClient调用SpringBoot项目的文件上传接口实现文件上传

news/2024/9/14 2:17:18/ 标签: http, springboot

1.导入httpclient的jar包

这里导入了httpclient、httpmime11

<?xml version="1.0" encoding="UTF-8"?>
<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><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.4</version><relativePath/></parent><groupId>com.liyh</groupId><artifactId>springboot-file</artifactId><version>0.0.1</version><name>springboot-file</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency><!-- 做断点下载使用 --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

 2.增加配置

在yml文件中增加配置

# 配置服务端口
server:port: 8018spring:servlet:multipart:#spring Boot中有默认的文件上传组件,在使用ServletFileUpload时需要关闭Spring Boot的默认配置enabled: true#設置單個文件的大小max-file-size: 1GB#設置單次請求文件的縂大小max-request-size: 10GB

3.编写文件上传接口

package com.liyh.controller;import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;@RestController
public class FileUploadController {private static final String UPLOAD_DIR = "D:\\path\\upload\\";@PostMapping("/api/upload")public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("description") String description,@RequestParam("userId") String userId) {if (file.isEmpty()) {return ResponseEntity.badRequest().body("No file provided");}try {System.out.println("description: " + description);System.out.println("userId: " + userId);Path destination = Paths.get(UPLOAD_DIR, file.getOriginalFilename());Files.copy(file.getInputStream(), destination);return ResponseEntity.ok("File uploaded successfully");} catch (IOException e) {return ResponseEntity.status(500).body("Failed to upload file");}}
}

4.使用httpclient进行单元测试

 

package com.health.manage;import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;import java.io.File;
import java.io.IOException;public class FileUploadTest {@Testpublic void testFileUpload() throws IOException {CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost("http://localhost:8018/api/upload");//httpPost.setHeader("Content-Type", "multipart/form-data");File fileToUpload = new File("E:\\tempUpload\\XXLJOB名称实验.xlsx");HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532).addPart("file", new FileBody(fileToUpload)).addTextBody("description", "This is a test file", ContentType.TEXT_PLAIN).addTextBody("userId", "12345", ContentType.TEXT_PLAIN).build();httpPost.setEntity(entity);try (CloseableHttpResponse response = httpClient.execute(httpPost)) {System.out.println("Response Code : " + response.getStatusLine().getStatusCode());String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");System.out.println("Response Body : " + responseString);} finally {httpClient.close();}}
}

后记 

如果您在一台电脑上使用httpclient测试文件上传接口,请你最好新建两个springboot工程

为啥要用httpclient方式来调用接口,不直接通过前端调用,一个很重要的原因是后台调用接口会比前端安全很多

 


http://www.ppmy.cn/news/1475474.html

相关文章

【面试题】Golang 之Channel底层原理 (第三篇)

目录 1.常见channel三大坑&#xff1a;死锁、内存泄漏、panic 1.死锁 1.只有生产者&#xff0c;没有消费者&#xff0c;或者反过来 2 生产者和消费者出现在同一个 goroutine 中 3 buffered channel 已满&#xff0c;且在同一个goroutine中 2.内存泄露 1 如何实现 gorout…

UE5 04-重新加载当前场景

在Unreal Engine 5 (UE5) 中&#xff0c;重新加载当前场景可以通过编程来实现。以下是一个简单的示例代码&#xff0c;展示了如何在UE5中重新加载当前场景&#xff1a; #include "Engine.h" #include "EngineUtils.h" #include "Kismet/GameplaySt…

Docker 容器内的php 安装redis扩展

1、https://pecl.php.net/package/redis 下载redis扩展 2、解压redis扩展包&#xff0c;然后通过命令拷贝到php容器 docker cp ~/nginx/redis-4.3.0/* myphp-fpm:/usr/src/php/ext/redis/ myphp-fpm是你的php容器 &#xff5e;/nginx/redis**** 是redi扩展包路径 3、进入php容…

【大模型LLM面试合集】大语言模型基础_Word2Vec

Word2Vec 文章来源&#xff1a;Word2Vec详解 - 知乎 (zhihu.com) 1.Word2Vec概述 Word2Vec是google在2013年推出的一个NLP工具&#xff0c;它的特点是能够将单词转化为向量来表示&#xff0c;这样词与词之间就可以定量的去度量他们之间的关系&#xff0c;挖掘词之间的联系。 …

超市管理系统 需求分析与设计 UML 方向

一、项目介绍 1.1项目背景 随着经济一体化和电子商务的迅速发展&#xff0c;网络传播信息的速度打破了传统信息传递的模式&#xff0c;互联网的高速发展和计算机应用在各个高校进展迅速&#xff0c;更多信息化产品的突飞猛进&#xff0c;让现代的管理模式也发生了巨大的变化&…

永磁同步电机控制算法--基于 SVM 的无磁链环 DTC

永磁同步电机无磁链环 DTC 通过控制定子磁链交轴分量来直接控制转矩&#xff0c;不再要求控制磁链幅值恒定&#xff0c;省去了传统 DTC 中的磁链环&#xff0c;不仅转矩响应更快&#xff0c;有效抑制了转矩脉动&#xff0c;而且提高了电机功率因数。但无磁链环 DTC 方案仍采用传…

vmware 虚拟机扩容 centos 硬盘扩容 kylinos v10扩容

1. 虚拟机先扩容 1.1 关机&#xff0c;并点击系统&#xff0c;让他是点选状态&#xff0c;但是没开机 1.2 右击&#xff0c;点击最下方设置&#xff0c;点击硬盘 1.3 点击扩展磁盘 1.4 选择你需要扩容的大小&#xff0c;数字为总大小 完成提示&#xff1a; 磁盘已成功扩展。您…

「Pytorch」roLabelImg 图像异常旋转 bug

在进行Yolo-obb 模型训练的时候需要标注旋转框&#xff0c;roLabelImg 是比较推荐的一款旋转框标注工具&#xff0c;既可以标注正常的矩形框&#xff0c;还可以标注旋转框 roLabelImg Github 地址&#xff1a;https://github.com/HumanSignal/labelImg 但是在使用过程中遇到了…

策略模式适用场景与具体实例解析

策略模式在多种场合下都能发挥其优势&#xff0c;尤其在需要根据不同条件或策略选择不同算法的场景中。下面是几个具体的适用场景及其对应的实例&#xff0c;以帮助进一步理解策略模式的实际应用。 1. 支付方式选择 在电子商务网站中&#xff0c;用户可以选择多种支付方式&am…

UDP 报文结构与注意事项全解析

在网络通信中&#xff0c;UDP&#xff08;User Datagram Protocol&#xff0c;用户数据报协议&#xff09;是一种无连接、不可靠的传输层协议。尽管它不如 TCP 那样提供可靠的传输服务&#xff0c;但在某些特定场景中&#xff0c;UDP 因其简单高效而备受青睐。 一、UDP 报文结…

WPF学习(3) -- 控件模板

一、操作过程 二、代码 <Window x:Class"学习.MainWindow"xmlns"http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x"http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d"http://schemas.microsoft.com/expressio…

.NET MAUI开源架构_1.学习资源分享

最近需要开发Android的App&#xff0c;想预研下使用.NET开源架构.NET MAUI来开发App程序。因此网上搜索了下相关资料&#xff0c;现在把我查询的结果记录下&#xff0c;方便后面学习。 1.官方文档 1.1MAUI官方学习网站 .NET Multi-Platform App UI 文档 - .NET MAUI | Micro…

上传图片到腾讯云和wangeditor的图片上传到腾讯云

1.创建src/utils/upload-file.js文件 import COS from cos-js-sdk-v5 import SparkMD5 from spark-md5 import { cosTmpsecret, cosConfig } from /api/upload // 通过后台获取临时密钥 let key // 配置 // const cosConfig { // // Bucket: xlcp-tong-1253334579, // …

WPF学习(6) -- WPF命令和通知

一 、WPF命令 1.ICommand代码 创建一个文件夹和文件 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input;namespace 学习.Command {public class MyCommand : ICommand{Acti…

旅游景区度假村展示型网站如何建设渠道品牌

景区、度假村、境外旅游几乎每天的人流量都非常高&#xff0c;还包括本地附近游等&#xff0c;对景区及度假村等固定高流量场所&#xff0c;品牌和客户赋能都是需要完善的&#xff0c;尤其是信息展示方面&#xff0c;旅游客户了解前往及查看信息等。 通过雨科平台建设景区度假…

本地部署,APISR: 动漫超分辨率技术

目录 引言 技术背景 APISR 的架构与原理 APISR 的主要特点 应用实例 本地部署 运行结果 结论 参考文献 GitHub - Kiteretsu77/APISR: APISR: Anime Production Inspired Real-World Anime Super-Resolution (CVPR 2024)APISR: Anime Production Inspired Real-World A…

百川工作手机实现销售管理微信监控系统

在瞬息万变的商业战场中&#xff0c;每一分效率的提升都是企业制胜的关键。传统销售管理模式已难以满足现代企业对精准、高效、合规的迫切需求。今天&#xff0c;让我们一同探索如何利用工作手机这一创新工具&#xff0c;为您的销售团队装上智能翅膀&#xff0c;开启销售管理的…

MySQL Binlog详解:提升数据库可靠性的核心技术

文章目录 1. 引言1.1 什么是MySQL Bin Log&#xff1f;1.2 Bin Log的作用和应用场景 2. Bin Log的基本概念2.1 Bin Log的工作原理2.2 Bin Log的三种格式 3. 配置与管理Bin Log3.1 启用Bin Log3.2 配置Bin Log参数3.3 管理Bin Log文件3.4 查看Bin Log内容3.5 使用mysqlbinlog工具…

张量笔记(4):张量网络

张量分解通常是将高维张量分解成一系列较低维的张量&#xff0c;表示能力相对较低。而张量网络可以表示复杂的高维数据结构&#xff0c;通过连接多个张量形成网络结构&#xff0c;可以更灵活地表示和处理复杂的数据关系。本节主要介绍HT和TT网络。 2.5.1 HT分解——首先我们引入…

Mac OS ssh 连接提示 Permission denied (publickey)

这错误有点奇葩&#xff0c;MacBook的IDE(vscode和pycharm)远程都连不上&#xff0c;terminal能连上&#xff0c;windows的pycharm能连上&#xff0c;见鬼了&#xff0c;所以肯定不是秘钥的问题了&#xff0c;查了好久竟然发现是权限的问题。。 chmod 400 ~/.ssh/id_rsa http…