day08 文件上傳 — 應(yīng)用服務(wù)器

  • 新建一個模塊,在創(chuàng)建時勾選web和Thymeleaf依賴
  • 新建一個upload.java文件
package com.springboot.upload.controller;

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;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 上傳文件控制器
 * 直接上傳到服務(wù)器
 * @author 26
 * 2019.3.25
 */

@Controller
public class UploadController {

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

    @PostMapping("/upload")
    public String fileUpload(@RequestParam("file")MultipartFile srcFile,
                             RedirectAttributes redirectAttributes){

        //生成系統(tǒng)時間
        SimpleDateFormat sf=new SimpleDateFormat("yyyyMMddHHmmss");
        String date=sf.format(new Date());

        //前端沒有選擇文件,srcFile為空
        if (srcFile.isEmpty()){
            redirectAttributes.addFlashAttribute("message", "請選擇一個文件");
            return "redirect:upload_status";
        }
        //選擇了文件,開始進行上傳操作
        try {
            //構(gòu)建上傳目標路徑
            File destFile=new File(ResourceUtils.getURL("classpath:").getPath());
            if (!destFile.exists()){
                destFile=new File("");
            }
            //輸出目標文件的絕對路徑
            System.out.println("file path:"+destFile.getAbsolutePath());
            //使用系統(tǒng)時間文件夾拼接目錄
            File upload=new File(destFile.getAbsolutePath(),date);
            //若目標文件夾不存在,則創(chuàng)建一個
            if (!upload.exists()){
                upload.mkdirs();
            }
            //生成UUID碼
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // 獲得文件原始名稱
            String fileName = srcFile.getOriginalFilename();
            // 獲得文件后綴名稱
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            // 生成最新的uuid文件名稱
            String newFileName = uuid + "."+ suffixName;
            System.out.println("完整的上傳路徑:"+upload.getAbsolutePath()+"/"+newFileName);
            //根據(jù)srcFile的大小,準備一個字節(jié)數(shù)組
            byte[] bytes=srcFile.getBytes();
            //通過項目路徑,拼接上傳路徑
            Path path=Paths.get(upload.getAbsolutePath()+"/"+newFileName);
            //最重要的一步,將源文件寫入目標地址
            Files.write(path,bytes);
            //將文件上傳成功的信息寫入messages
            redirectAttributes.addFlashAttribute("message", "文件上傳成功!"+newFileName);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:upload_status";
    }

    //匹配upload_status頁面
    @GetMapping("/upload_status")
    public String uploadStatusPage(){
        return "upload_status";
    }
}
  • 在resources的templates下新建upload.html文件
<!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>
  • 同目錄中新建upload_status.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}"/>
</body>
</html>
  • 運行Application文件,打開瀏覽器localhost:8080
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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