Spring Boot文件上傳

文件上傳是項目開發(fā)中的常見操作。一般分為如下幾種解決方案

  • 直接上傳到應用服務器
  • 上傳到阿里云、七牛云等OSS服務器
  • 圖片轉(zhuǎn)成Base64后傳到服務器

本例以第一種為例,實現(xiàn)將本地圖片上傳到服務器指定路徑的基礎功能
新建一個module,命名為file-upload,勾選web、Thymeleaf依賴

pom.xml

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

在resources的templates目錄下建兩個html文件,如圖所示的項目結(jié)構

image

application.properties配置一下上傳參數(shù)

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB

編寫UploadController,映射上傳請求

package com.springboot.fileupload.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class UploadController {
    private static String UPLOADED_FOLDER = "E:/temp/";

    @GetMapping("/")
    public String index() {
        return "upload";
    }

    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "請選擇一個文件");
            return "redirect:upload_status";
        }

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message",
                    "文件成功上傳!" + file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/upload_status";
    }

    @GetMapping("/upload_status")
    public String uploadStatus() {
        return "upload_status";
    }
}

upload.html文件

<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<body>
<h1>Spring Boot 文件上傳示例</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <br>
    <br>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

upload_status.html文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot - 文件上傳狀態(tài)</h1>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
</body>
</html>

運行啟動主類,http://localhost:8080定向到了upload.html頁面

image

選擇一個本地文件,點擊提交,將文件提交到了服務器指定目錄,頁面跳轉(zhuǎn)到upload_status.html,提示上傳成功

image
image

image.png

如果要把上傳的路徑跟著項目,如在static目錄下的upload文件夾,則需要更改UploadController代碼
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class UploadController {

@GetMapping("/")
public String index() {
    return "upload";
}

@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile srcFile,
                               RedirectAttributes redirectAttributes) {
    if (srcFile.isEmpty()) {
        redirectAttributes.addFlashAttribute("message", "請選擇一個文件");
        return "redirect:upload_status";
    }
    try {
        File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!destFile.exists()) {
            destFile = new File("");
        }
        System.out.println("file path:" + destFile.getAbsolutePath());
        File upload = new File(destFile.getAbsolutePath(), "static/");
        if (!upload.exists()) {
            upload.mkdirs();
        }
        System.out.println("upload url:" + upload.getAbsolutePath());
        Path path = Paths.get(upload.getAbsolutePath() + "/" + srcFile.getOriginalFilename());
        byte[] bytes = srcFile.getBytes();
        Files.write(path, bytes);
        redirectAttributes.addFlashAttribute("message",
                "文件成功上傳!" + srcFile.getOriginalFilename());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:/upload_status";
}

@GetMapping("/upload_status")
public String uploadStatus() {
    return "upload_status";
}

}

會將文件上傳到target/classes/static目錄下,如圖

image
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 文件上傳時Web應用最為常見的功能之一,傳統(tǒng)的文件上傳需要定制一個特殊的form表單來上傳文件,以上傳圖片為例,常...
    ramostear閱讀 1,903評論 0 1
  • 文件上傳是項目開發(fā)中的常見操作。一般分為如下幾種解決方案 直接上傳到應用服務器 上傳到阿里云、七牛云等OSS服務器...
    陶然然_niit閱讀 583評論 0 9
  • 三種上傳方式 直接上傳到應用服務器 上傳到oss(內(nèi)容存儲在服務器)如 阿里云 七牛云 前端將圖片轉(zhuǎn)成Base64...
    青檸_efca閱讀 311評論 0 0
  • 雨中的女人,身影都是彷徨 稀疏的睫毛,瑩光點點 昏黃的眼里,水潤汪汪 是雨絲還是淚滴 雨中女人 為何不把手中的傘撐...
    沐葉_93f1閱讀 311評論 0 2
  • 前言:能夠使mybatis-plus像mybatis一樣在xml中寫SQL前提是原本可以在項目中正常使用mybat...
    samgroves閱讀 66,444評論 13 2

友情鏈接更多精彩內(nèi)容