1. 程式人生 > 其它 >springboot-簡單圖片上傳

springboot-簡單圖片上傳

springboot-簡單圖片上傳

在application配置檔案中配置路徑對映

file.upload.path=E://images/
file.upload.path.relative=/images/**

編寫index.html

<!DOCTYPE html>
<html lang="en-US" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>photo</title>
</head>

<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" accept="image/*">
        <br>
        <input type="submit" value="上傳" class="btn btn-success">
    </form>
    [[${filename}]]
    <br>
    <img th:src="@{${filename}}" alt="圖片">
</body>
</html>

編寫controller層方法及URL

@RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) {
        // 獲取上傳檔名
        String filename = file.getOriginalFilename();
        try {
            //寫入本地檔案
            file.transferTo(new File( "E:\\images\\"+ filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 將src路徑傳送至html頁面
        model.addAttribute("filename", "/images/"+filename);
        return "index";
    }
測試