前言
学习一下怎么用 SpringBoot 实现一个接收文件上传的服务。
以前用过 PHP,知道 PHP 实现这个功能很简单。
今天来看一下用 SpringBoot 难度如何。
第一个文件上传的例子
本文将实现一个应用,可以接收 HTTP multi-part 文件上传。
自动生成框架
新建一个 SpringBoot 项目 test-uploading-files
,选中 web
和 thymeleaf
组件,会自动生成 pom.xml
文件如下:
pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>test-uploading-files</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test-uploading-files</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application
上传业务逻辑
上传业务逻辑由两部分组成,上传的 Controller,以及存储相关的 Bean。
上传的 Controller
存储接口
存储接口实现
这里简单实现了存储接口,将文件保存在了本地的临时目录中。
上传页面
uploadForm.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
<div>
<form method="POST" enctype="multipart/form-data" action="/">
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
</div>
<div>
<ul>
<li th:each="file : ${files}">
<a th:href="${file}" th:text="${file}" />
</li>
</ul>
</div>
</body>
</html>
结果验证
上传文件
打开页面 http://localhost:8080/
选择,上传,会提示上传成功
You successfully uploaded nls-sample.wav!
File to upload:
http://localhost:8080/files/nls-sample.wav1535611762856
浏览器上传请求头
T ::1:51601 -> ::1:8080 [AP]
POST / HTTP/1.1.
Host: localhost:8080.
Connection: keep-alive.
Content-Length: 122127.
Cache-Control: max-age=0.
Origin: http://localhost:8080.
Upgrade-Insecure-Requests: 1.
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryAFEBo1WOUGX30iNO.
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8.
Referer: http://localhost:8080/.
Accept-Encoding: gzip, deflate, br.
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8.
Cookie: JSESSIONID=697B47A0C99C9EB33EFBD7402D6A8284.
.
T ::1:51601 -> ::1:8080 [A]
------WebKitFormBoundaryAFEBo1WOUGX30iNO.
Content-Disposition: form-data; name="file"; filename="nls-sample.wav".
Content-Type: audio/wav.
Java 上传请求头
POST / HTTP/1.1.
File-Name: : nls-sample.wav.
Content-Length: 122161.
Content-Type: multipart/form-data; boundary=4t50V2AKusf3syAD1cwtOyGDOa6CRp.
Host: 30.1.1.33:8080.
Connection: Keep-Alive.
User-Agent: Apache-HttpClient/4.3.5 (java 1.5).
Accept-Encoding: gzip,deflate.
.
--4t50V2AKusf3syAD1cwtOyGDOa6CRp.
Content-Disposition: form-data; name="file"; filename="nls-sample.wav".
Content-Type: application/octet-stream.
Content-Transfer-Encoding: binary.
Java 上传文件的多种方式
使用 MultipartEntity
// 上传
String uploadUrl;
{
File file = new File("/Users/note/tmp/nls-sample.wav");
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new FileBody(file));
HttpResponse response = Request.Post("http://" + host + "/").addHeader("File-Name: ", file.getName())
.body(entity).execute().returnResponse();
if (response.getStatusLine().getStatusCode() == 200) {
uploadUrl = EntityUtils.toString(response.getEntity());
} else {
System.out.println(response.getStatusLine().getStatusCode());
}
}
不过 MultipartEntity 已经过时了,推荐使用下面的 MultipartEntityBuilder
使用 MultipartEntityBuilder
// 模拟表单上传
HttpEntity entity = MultipartEntityBuilder.create().addPart("file", new FileBody(file)).build();
单文件上传
// 模拟表单上传
HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody("file", file).build();
头信息为
POST / HTTP/1.1.
File-Name: : nls-sample.wav.
Content-Length: 121940.
Host: 30.25.104.69:8080.
Connection: Keep-Alive.
User-Agent: Apache-HttpClient/4.3.5 (java 1.5).
Accept-Encoding: gzip,deflate.
.
参考
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于