SpringBoot极简教程 · Spring Boot SpringBoot之旅IT技术篇

SpringBoot-05-之上传文件

2018-07-16  本文已影响23人  e4e52c116681

需要使用引擎模板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
 * 邮箱:1981462002@qq.com
 * 说明:文件上传控制器
 */
@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
上一篇下一篇

猜你喜欢

热点阅读