SpringBoot第03天_檔案上傳功能_示範觸發RestController做檔案上傳請求接收

可編寫靜態資源test.html 
來去demo上傳頁面
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h1>這是test html靜態資源</h1>
  <!--<img src="images/logo.png" >-->
  <h1>檔案上傳</h1>
  <form action="upload" method="post" enctype="multipart/form-data">
      請選擇文件:<input type="file" name="attach"> <br/>
      <input type="submit" value="開始上傳" />
  </form>
</body>
</html>

這邊我們添加一個RestController做檔案上傳請求接收

UploadController.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.example.demo2_themeleaf;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadController {
    Map<String,Object> result = new HashMap<String,Object>();

    @RequestMapping("/upload")
    public Map<String,Object> upload(@RequestParam("attach")MultipartFile file) throws IOException {
        //文件處理
        System.out.println("檔案原始名稱:" + file.getOriginalFilename());
        System.out.println("檔案類型:" + file.getContentType());

        //存到硬碟某路徑
        file.transferTo(new File("C:/img/upload" + file.getOriginalFilename()));

        result.put("success",true);

        return result;
    }
}
















留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題