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: 8018
spring:
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 {
@Test
public 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方式来调用接口,不直接通过前端调用,一个很重要的原因是后台调用接口会比前端安全很多
原文地址:https://blog.csdn.net/wodetongnian/article/details/140408022
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!