基于 SpringBoot 的文件上傳

上傳文件是互聯(lián)網中常常應用的場景之一,最典型的情況就是上傳頭像等。

主要有以下幾種方式

  • 直接上傳到應用服務器

  • 上傳到 OSS 內容存儲服務器(阿里云、七牛云)

  • 前端將圖片轉成 Base64 編碼上傳

前后端不分離

創(chuàng)建 upload 模塊

添加 web、thymeleaf 依賴

配置上傳屬性

配置上傳屬性 application.properties,指定上傳文件大小限制等

#文件上傳的配置
spring.servlet.multipart.max-file-size=10MB

編寫控制器

通過 java.nio 實現(xiàn)文件的上傳

//這是一個上傳文件控制器
@Controller
public class UploadController {
    //指定一個臨時路徑作為上傳目錄
    //private static String UPLOAD_FOLDER = "C:\\Users\\Desktop\\UPLOAD\\";

    //遇到http://localhost:8080,則跳轉至upload.html頁面
    @GetMapping("/")
    public String index() {
        return "upload";
    }

    @PostMapping("upload")
    public String fileUpload(@RequestParam("file") MultipartFile srcFile, RedirectAttributes redirectAttributes) {
        //前端沒有選擇文件,srcFile為空
        if (srcFile.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "請選擇一個文件");
            return "redirect:upload_status";
        }
        //選擇了文件,開始上傳操作
        try {
            //構建上傳目標路徑,找到了項目的target的classes目錄
            File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!destFile.exists()) {
                destFile = new File("");
            }
            //輸出目標文件的絕對路徑
            System.out.println("file path:" + destFile.getAbsolutePath());
            //拼接子路徑,以時間日期創(chuàng)建文件夾
            Date date = new Date();
            File upload = new File(destFile.getAbsolutePath(), "static/" + new SimpleDateFormat("yyyyMMdd/").format(date));
            //若目標文件夾不存在,則創(chuàng)建
            if (!upload.exists()) {
                upload.mkdirs();
            }
            //使用uuid重命名文件
            String fileName = srcFile.getOriginalFilename();
            String fileExtension = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            System.out.println("完整的上傳路徑:" + upload.getAbsolutePath() + "/" + fileExtension);
            //根據srcFile大小,準備一個字節(jié)數組
            byte[] bytes = srcFile.getBytes();
            //拼接上傳路徑
            //Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
            //通過項目路徑,拼接上傳路徑
            Path path = Paths.get(upload.getAbsolutePath() + "/" + UUIDUtil.getUUID32() + fileExtension);
            //** 開始將源文件寫入目標地址
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message", "文件上傳成功" + UUIDUtil.getUUID32() + fileExtension);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:upload_status";
    }

    //匹配upload_status頁面
    @GetMapping("/upload_status")
    public String uploadStatusPage() {
        return "upload_status";
    }
}

控制器配置好 thymeleaf 的頁面跳轉及信息顯示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Spring Boot 文件上傳</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上傳">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上傳狀態(tài)顯示</title>
</head>
<body>
<h2>Spring Boot 的文件顯示狀態(tài)</h2>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
</body>
</html>

運行項目,上傳文件,觀察結果

前后端分離

后端

只需要將控制器的注解改為 @RestController

前端

<template>
  <div class="container">
    <h2>任務中心</h2>
    <div class="preview"><img :src="imgUrl"></div>
    <form>
      <div class="upload">
        選擇文件
        <input type="file" @change="getFile($event)">
      </div>
      <br>
      <button @click="submit($event)" class="sub-btn">提交</button>
    </form>
  </div>
</template>


<script>
export default {
  name: "Task",
  data() {
    return {
      imgUrl:
        "https://static-cdn-oss.mosoteach.cn/mssvc/icons/icon_cc_cover1@2x.png",
      file: ""
    };
  },
  methods: {
    getFile: function(event) {
      this.file = event.target.files[0];
      var windowURL = window.URL || window.webkitURL;
      alert(windowURL.createObjectURL(this.file));
      this.imgUrl = windowURL.createObjectURL(this.file);
    },
    submit: function(event) {
      event.preventDefault();
      let formData = new FormData();
      formData.append("file", this.file);
      this.$http
        .post("http://localhost:8081/upload", formData)
        .then(function(response) {
          alert(response.data);
          this.imgUrl = response.data;
        });
    }
  }
};
</script>
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容