1. 程式人生 > >Springboot 之 多檔案上傳-知識林

Springboot 之 多檔案上傳-知識林

本文章來自【知識林】

檔案上傳在各種網站平臺上應用都非常廣泛,這篇文章將講述在Springboot中是如何完成檔案上傳的,Springboot是打包執行的,上傳後的檔案又該何去何從?

  • pom.xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
    <relativePath
/>
<!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId
>
org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId
>
</dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> </dependencies>

說明:頁面模板還是使用Thymeleaf,檔案上傳工具使用Apache的commons-io

  • application.properties
server.port=1117
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false

web.upload-path=D:/temp/upload/study17/

spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
  classpath:/static/,classpath:/public/,file:${web.upload-path}
  • Controller控制器
@Controller
public class IndexController {

    //獲取上傳的資料夾,具體路徑參考application.properties中的配置
    @Value("${web.upload-path}")
    private String uploadPath;

    /**
     * GET請求
     * 上傳頁面,也將顯示已經存在的檔案
     * @param model
     * @return
     */
    @GetMapping(value = "/index")
    public String index(Model model) {
        //獲取已存在的檔案
        File [] files = new File(uploadPath).listFiles();
        model.addAttribute("files", files);
        return "web/index";
    }

    /**
     * POST請求
     * @param request
     * @param files
     * @return
     */
    @PostMapping(value = "index")
    public String index(HttpServletRequest request, @RequestParam("headimg")MultipartFile[] files) {
        //可以從頁面傳引數過來
        System.out.println("name====="+request.getParameter("name"));
        //這裡可以支援多檔案上傳
        if(files!=null && files.length>=1) {
            BufferedOutputStream bw = null;
            try {
                String fileName = files[0].getOriginalFilename();
                //判斷是否有檔案且是否為圖片檔案
                if(fileName!=null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {
                    //建立輸出檔案物件
                    File outFile = new File(uploadPath + "/" + UUID.randomUUID().toString()+ getFileType(fileName));
                    //拷貝檔案到輸出檔案物件
                    FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if(bw!=null) {bw.close();}
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/index";
    }

    /**
     * 判斷檔案是否為圖片檔案
     * @param fileName
     * @return
     */
    private Boolean isImageFile(String fileName) {
        String [] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        if(fileName==null) {return false;}
        fileName = fileName.toLowerCase();
        for(String type : img_type) {
            if(fileName.endsWith(type)) {return true;}
        }
        return false;
    }

    /**
     * 獲取檔案字尾名
     * @param fileName
     * @return
     */
    private String getFileType(String fileName) {
        if(fileName!=null && fileName.indexOf(".")>=0) {
            return fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        return "";
    }
}

說明: @RequestParam("headimg")MultipartFile[] files這裡的headimg是根據頁面上File inputname屬性而定。

  • index.html
<!DOCTYPE html>
<html lang="zh-CN"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>檔案上傳</title>
    </head>
    <body>
        <h2>已有檔案:</h2>
        <p th:each="file : ${files}">
            [站外圖片上傳中……(2)],檔名稱:<span th:text="${file.name}"></span>
        </p>
        <hr/>
        <form method="post" enctype="multipart/form-data">
            暱稱:<input name="name" type="text"/>
            <br/>
            頭像:<input name="headimg" type="file"/>
            <br/>
            <button type="submit">確定上傳</button>
        </form>
    </body>
</html>

注意:<input name="headimg" type="file"/>這裡的headimg決定了Controller中@RequestParam("headimg")的值。如果有多個<input name="headimg" type="file"/>將是多檔案上傳。

  • 頁面截圖

通過上面例子上傳兩張圖片後的效果:

多檔案上傳-知識林

本文章來自【知識林】