服务端: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
spring:servlet:multipart:max-file-size: 1000MBmax-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);}
}