SpringBoot實現文件上傳


前言參考:快速開發第一個SpringBoot應用

這篇文章會講解如何使用SpringBoot完成一個文件上傳的過程,並且附帶一些SpringBoot開發中需要注意的地方

首先我們寫一個文件上傳的html頁面:picUpload.html

<!DOCTYPE HTML>
<html>
    <head>
        <title>pictureUploading</title>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8 ">
    </head>
    <body>
        <form enctype="multipart/form-data" method="post" action="/upload">
            文件:<input type="file" name="fileUpload"/>
            <input type="submit" value="上傳"/>
        </form>
    </body>
</html>

注意form標簽里的enctype屬性必須指定為:multipart/form-data。

下面我們看看通過Quick Start得到的項目的初始目錄結構:
這里寫圖片描述

SpringBoot官方文檔告訴我們,statis這個目錄里面應該存放一些靜態文件,比如 css、js、image並且可以直接被外部訪問到。而templates這個目錄則存放一些靜態頁面,如jsp、html、ftl。並且template這個目錄里的內容外部是訪問不到的。按照規范,我們將picUpload.html文件放到templates目錄下。

現在通過:localhost:8080/index.html是訪問不到該頁面的。按照以前學習SpringMVC的經驗,應該寫一個controller,通過這個controller跳轉到picUpload.html頁面上去,再返回給用戶。

下面我們新建一個controller,用做頁面的跳轉:

@Controller
public class ToHtmlController {
    @RequestMapping("/picUpload")
    public String picUpload(){
        return "picUpload";
    }
}

此時如果我們啟動項目,並訪問localhost:8080/picUpload這個url,頁面會報錯如下:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jun 04 19:10:46 CST 2018
There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [picUpload]: would dispatch back to the current handler URL [/picUpload] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

注意最后一句提示,意思就是我們沒有指明模板引擎,這里我們使用thymeleaf,在pom.xml文件中添加如下依賴:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

然后啟動項目,訪問localhost:8080/picUpload,看到頁面如下:
這里寫圖片描述

當選擇完文件,點擊上傳按鈕后,form表單會按照action屬性值的url進行后端訪問action="/upload",此時我們應該寫一個controller來接收前端傳來的圖片,並將圖片放到項目的static目錄下。

圖片處理controller如下:

/** * 圖片上傳 * @author 吳洋 * */
@RestController
public class PicUploadController {

    @PostMapping("/upload")
    public Object upload(MultipartFile fileUpload){
        //獲取文件名
        String fileName = fileUpload.getOriginalFilename();
        //獲取文件后綴名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //重新生成文件名
        fileName = UUID.randomUUID()+suffixName;
        //指定本地文件夾存儲圖片
        String filePath = "D:/SpringBoot/demo/src/main/resources/static/";
        try {
            //將圖片保存到static文件夾里
            fileUpload.transferTo(new File(filePath+fileName));
            return new Massage(0,"success to upload");
        } catch (Exception e) {
            e.printStackTrace();
            return new Massage(-1,"fail to upload");
        } 
    }
}

這里我新建了一個Message類,來向前端返回是否上傳成功的信息。

public class Massage {
    //0表示成功;-1表示失敗
    int status;
    //向前端返回的內容
    String massage;
    public Massage() {
        super();
    }
    public Massage(int status, String massage) {
        super();
        this.status = status;
        this.massage = massage;
    }
    //get/set方法
}

此時我們啟動項目,並訪問localhost:8080/picUpload,選擇圖片,點擊上傳。頁面返回如下:
這里寫圖片描述
說明圖片上傳成功了,refresh項目,可以看到static目錄下出現了我們上傳的圖片,並且名稱也隨機改變了。
這里寫圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM