您的位置:首页 > 教育 > 锐评 > HttpClient调用SpringBoot项目的文件上传接口实现文件上传

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

2024/10/5 16:21:00 来源:https://blog.csdn.net/wodetongnian/article/details/140408022  浏览:    关键词: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方式来调用接口,不直接通过前端调用,一个很重要的原因是后台调用接口会比前端安全很多

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com