首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot-05-之上传文件

SpringBoot-05-之上传文件

作者头像
张风捷特烈
发布2018-09-26 17:57:41
5250
发布2018-09-26 17:57:41
举报

需要使用引擎模板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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.07.16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.新建表单网页:templates/upfile.html
  • 2.控制器:toly1994.com.toly01.controller.UpFileController
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档