springboot 中檔案的上傳和下載

unix_sky發表於2020-11-09

.上傳下載

1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>檔案上傳下載案例</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
    <label>賬號:</label><input type="text" name="username"><br/>
    <label>照片:</label><input type="file" name="upload"><br/>
    <input type="submit" value="提交">
</form>
<h2><a href="/download">檔案下載</a></h2>
</body>
</html>

2. java程式碼

  @RequestMapping("/upload")
    public String upload(MultipartFile uploadFile,String username) throws IOException {
        System.out.println("userName:" + username + " 檔名稱:" + uploadFile.getOriginalFilename());
        uploadFile.transferTo(new File("d:/" ,uploadFile.getOriginalFilename()));
        return "success ...";
    }

 @RequestMapping("/download")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response){
        File file = new File("d://CSDN Java架構師成長路徑V12.0.jpg");
        // 設定響應的頭和客戶端儲存的檔名
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
        InputStream in = null;
        ServletOutputStream out = null;
        try {
            // 檔案的複製
            in = new FileInputStream(file);
            out = response.getOutputStream();
            // 迴圈讀取
            byte[] b = new byte[1024];
            int length = 0;
            while((length = in.read(b)) > 0){
                out.write(b,0,length);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

3.配置:

spring.servlet.multipart.enabled=true
 #設定單個檔案上傳的大小
spring.servlet.multipart.max-file-size=200MB
#設定一次上傳檔案總的大小
spring.servlet.multipart.max-request-size=200MB

相關文章