天天看點

SpringBoot-05-之上傳檔案

需要使用引擎模闆thymeleaf,如果不清楚,可見 04--SpringBoot之模闆引擎--thymeleaf
1.建立表單網頁:templates/upfile.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
    檔案上傳<input type="file" name="file"/>
    <input type="submit" value="上傳"/>
</form>
</body>
</html>
           
2.控制器:toly1994.com.toly01.controller.UpFileController
/**
 * 作者:張風捷特烈
 * 時間:2018/5/29:23:15
 * 郵箱:[email protected]
 * 說明:檔案上傳控制器
 */
@Controller
public class UpFileController {
    @GetMapping("/upload_html")
    public String uploadHtml() {
        return "upfile";
    }

    //處理檔案上傳
    @PostMapping(value = "/upload")
    public @ResponseBody
    String uploadImg(
            @RequestParam("file") MultipartFile file, HttpServletRequest request) {

        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();//擷取名字

        String path = "F:/test";
        File dest = new File(path + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判斷檔案父目錄是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //儲存檔案
            return "上傳成功!";
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return "上傳失敗!";
        }
    }
}
           

upload.png

繼續閱讀