SpringBoot實現文件上傳

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

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

首先咱們寫一個文件上傳的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。java

下面咱們看看經過Quick Start獲得的項目的初始目錄結構:
這裏寫圖片描述spring

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

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

下面咱們新建一個controller,用作頁面的跳轉:dom

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

此時若是咱們啓動項目,並訪問localhost:8080/picUpload這個url,頁面會報錯以下:jsp

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.)spring-boot

注意最後一句提示,意思就是咱們沒有指明模板引擎,這裏咱們使用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目錄下出現了咱們上傳的圖片,而且名稱也隨機改變了。
這裏寫圖片描述

相關文章
相關標籤/搜索