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

HttpClient调用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.lryc.cn/news/399471.html

相关文章:

  • [leetcode]kth-smallest-element-in-a-sorted-matrix 有序矩阵中第k小元素
  • 【经典面试题】是否形成有环链表
  • Flask 用 Redis 缓存键值对-实例
  • 我的世界1.21多种服务端开服教程,原版/Forge/Fabric/Paper/Mohist...,Minecraft开服教程
  • docker安装nginx并配置https
  • 永磁同步电机控制算法--基于 SVM 的无磁链环 DTC
  • 如何避免在 Docker 容器中遇到 MAC 地址冲突和 IP 地址冲突的问题
  • arm64架构下源码编译安装kafka —— 筑梦之路
  • LabVIEW前面板占满整个屏幕(转)
  • Promise.all、any、race和allSettled的相同点与不同点与应用场景
  • Ubuntu下如何设置程序include搜索路径及链接路径
  • FLinkCDC引起的生产事故(二)
  • 【产品经理】WMS多仓调拨转移说明
  • 每日一练:奇怪的TTL字段(python实现图片操作实战)
  • 【Java开发实训】day03——方法的注意事项
  • HarmonyOS NEXT:一次开发,多端部署
  • Bilibili Android一二面凉经(2024)
  • 数据库内核研发学习之路(一)
  • LSTM:深度学习中的时间序列处理大师
  • T113-i系统启动速度优化方案
  • ArcGis将同一图层的多个面要素合并为一个面要素
  • 微软Win11 24H2七月更新补丁KB5040435发布!附下载
  • iOS 开发中不常见的专业术语
  • 【中项第三版】系统集成项目管理工程师 | 第 4 章 信息系统架构④ | 4.7
  • Time to say GoodBye
  • C语言之指针的奥秘(二)
  • 嵌入式linux系统内核启动过程分享
  • RK3568笔记三十五:LED驱动开发测试
  • pnpm 如何安装指定版本
  • LeetCode 240 搜索二维矩阵||