springboot 檔案上傳下載

hayhead發表於2020-12-17

1、引入依賴

引入web和thymeleaf依賴

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

2、html頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<h3>多檔案上傳</h3>
<form action="/uploads" method="post" enctype="multipart/form-data">
    <input type="file"   name="mulUploadFile" value="請選擇檔案" multiple><!-- multiple支援多檔案上傳 -->
    <input type="submit" value="上傳檔案">
</form>

<h3>檔案下載</h3>
<a href="/download?filename=3.jpg" >公孫離.jpg</a>
</body>

</html>

3、controller

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class FileUploadDown {

    @ResponseBody
    @PostMapping("/uploads")
    public String uploads(MultipartFile[] mulUploadFile , HttpServletRequest req){

        int i;
        for (i = 0; i < mulUploadFile.length; i++) {
            if(mulUploadFile[i].isEmpty()){
                return "上傳失敗!檔案不能為空!";
            }
            //獲取原檔名
            String fileName = mulUploadFile[i].getOriginalFilename();
            //目標路徑
            String filePath = "E:/Temp/";
            File file = new File(filePath+fileName);
            try {
                mulUploadFile[i].transferTo(file);
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }
        if(i == mulUploadFile.length) return "檔案上傳成功";
        else return "檔案上傳失敗";
    }

    @GetMapping("/download")
    public String download(HttpServletResponse response , HttpServletRequest request){

        try{
        // 1.得到要下載的檔名稱
        String filename = request.getParameter("filename");
        filename = new String(filename.getBytes("iso8859-1"), "utf-8"); // 解決中文亂碼
        //檔案所在位置
        File file = new File("E:\\", filename);
        if (file.exists()) {
            // 檔案存在,完成下載
            // 下載注意事項1--設定下載檔案的mimeType
            String mimeType = request.getServletContext().getMimeType(filename);
            response.setContentType(mimeType);
            // 其它瀏覽器
            filename = URLEncoder.encode(filename, "utf-8");

            // 下載注意事項2--永遠是下載 設定以附件的形式進行開啟下載
            response.setHeader("content-disposition", "attachment;filename="
                    + filename);

            FileInputStream fis = new FileInputStream(file); // 讀取要下載檔案的內容
            OutputStream os = response.getOutputStream();// 將要下載的檔案內容通過輸出流寫回到瀏覽器
            int len = -1;
            byte[] b = new byte[1024 * 100];

            while ((len = fis.read(b)) != -1) {
                os.write(b, 0, len);
                os.flush();
            }
            os.close();
            fis.close();
        } else {
            throw new RuntimeException("下載資源不存在");
        }
        }catch (IOException e){

        }
        return "";
    }
}

4、application.properties

# 上傳檔案總的最大值
spring.servlet.multipart.max-request-size=10MB
# 單個檔案的最大值
spring.servlet.multipart.max-file-size=10MB

相關文章