SpringBoot 文件上传初体验

本贴最后更新于 2066 天前,其中的信息可能已经事过景迁

前言

学习一下怎么用 SpringBoot 实现一个接收文件上传的服务。

以前用过 PHP,知道 PHP 实现这个功能很简单。

今天来看一下用 SpringBoot 难度如何。

第一个文件上传的例子

本文将实现一个应用,可以接收 HTTP multi-part 文件上传。

自动生成框架

新建一个 SpringBoot 项目 test-uploading-files,选中 webthymeleaf 组件,会自动生成 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

package com.example.testuploadingfiles;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestUploadingFilesApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestUploadingFilesApplication.class, args);
    }
}

上传业务逻辑

上传业务逻辑由两部分组成,上传的 Controller,以及存储相关的 Bean。

上传的 Controller

package com.example.testuploadingfiles;

import java.io.IOException;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.example.testuploadingfiles.storage.StorageService;

@Controller
public class FileUploadController {

    private final StorageService storageService;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {

        model.addAttribute("files", storageService.loadAll().map(
            path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
                "serveFile", path.getFileName().toString()).build().toString())
            .collect(Collectors.toList()));

        return "uploadForm";
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = storageService.loadAsResource(filename);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }

    @PostMapping("/")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        try {
            storageService.store(file);
            System.out.println("上传完成: " + file.getOriginalFilename());
            redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + file.getOriginalFilename() + "!");

            return "redirect:/";
        } catch (Exception e){
            e.printStackTrace();
            return "ok";
        }
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<?> handleStorageFileNotFound(RuntimeException exc) {
        return ResponseEntity.notFound().build();
    }
}

存储接口

package com.example.testuploadingfiles.storage;

import java.nio.file.Path;
import java.util.stream.Stream;

import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}

存储接口实现

这里简单实现了存储接口,将文件保存在了本地的临时目录中。

package com.example.testuploadingfiles.storage;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

@Service
public class StorageServiceImpl implements StorageService {

    // 文件保存的路径
    private final Path rootLocation = Paths.get("/tmp/upload");

    @Override
    public void init() {
        // 初始化目录, 保证目录存在
        try {
            if (!Files.exists(rootLocation)) {
                Files.createDirectory(rootLocation);
            }
        } catch (IOException e) {
            throw new RuntimeException("Could not initialize storage", e);
        }
    }

    @Override
    public void store(MultipartFile file) {

        // 将文件保存到目录中
        try {
            if (file.isEmpty()) {
                throw new RuntimeException("Failed to store empty file " + file.getOriginalFilename());
            }
            // 测试时,为了避免重名,末尾加了时间戳.
            String dstFile = file.getOriginalFilename() + System.currentTimeMillis();
            Files.copy(file.getInputStream(), this.rootLocation.resolve(dstFile));
        } catch (IOException e) {
            throw new RuntimeException("Failed to store file " + file.getOriginalFilename(), e);
        }
    }

    @Override
    public Stream<Path> loadAll() {
        // 遍历目录下的文件
        try {
            return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(path -> this.rootLocation.relativize(path));
        } catch (IOException e) {
            throw new RuntimeException("Failed to read stored files", e);
        }
    }

    @Override
    public Path load(String filename) {
        // 读取指定文件的路径
        return rootLocation.resolve(filename);
    }

    @Override
    public Resource loadAsResource(String filename) {
        // 读取指定路径的内容
        try {
            Path file = load(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new RuntimeException("Could not read file: " + filename);

            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("Could not read file: " + filename, e);
        }
    }

    @Override
    public void deleteAll() {
        // 删除目录
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }
}

上传页面

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.
.

参考

  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3168 引用 • 8207 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...