1. 程式人生 > >詳細全面的 SpringBoot 檔案上傳

詳細全面的 SpringBoot 檔案上傳

這些天忙著刷題,又怕遺忘了spring boot, 所以抽出一點時間折騰折騰,加深點印象。
spring boot 的檔案上傳與 spring mvc 的檔案上傳基本一致,只需注意一些配置即可。
環境要求: Spring Boot v1.5.1.RELEASE + jdk1.7 + myeclipse

1).引入thymeleaf,支援頁面跳轉

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

2).在 src/main/resources 目錄下新建 static 目錄和 templates 目錄。 static存放靜態檔案,比如 css、js、image… templates 存放靜態頁面。先在templates 中新建一個 uploadimg.html

<!DOCTYPE html>
<html>
  <head>
    <title
>
uploadimg.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3"></meta> <meta name="description" content="this is my page"></meta> <meta name="content-type" content="text/html; charset=UTF-8"></meta> <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head> <body> <form enctype="multipart/form-data" method="post" action="/testuploadimg"> 圖片<input type="file" name="file"/> <input type="submit" value="上傳"/> </form> </body> </html>

3).在 controller 中寫兩個方法,一個方法跳轉到上傳檔案的頁面,一個方法處理上傳檔案

//跳轉到上傳檔案的頁面
    @RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
    public String goUploadImg() {
        //跳轉到 templates 目錄下的 uploadimg.html
        return "uploadimg";
    }

    //處理檔案上傳
    @RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
    public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        /*System.out.println("fileName-->" + fileName);
        System.out.println("getContentType-->" + contentType);*/
        String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
        try {
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
            // TODO: handle exception
        }
        //返回json
        return "uploadimg success";
    }

4).在上面中,我將檔案上傳的實現寫在工具類 FileUtil 的 uploadFile 方法中

public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
        File targetFile = new File(filePath);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }       
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

這裡寫圖片描述

上傳檔案後:

這裡寫圖片描述

在應用的 src/main/webapp/imgupload 目錄下

這裡寫圖片描述

6).如果上傳的檔案大於 1M 時,上傳會報錯檔案太大的錯誤,在 application.properties 中設定上傳檔案的引數即可

spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=100Mb