SpringBoot 文件上传

springboot文件上传 MultipartFile file,源自SpringMVC

  (1)静态页面放在static目录下

(2)直接访问:localhost:8080/upload.html

<form enctype="multipart/form-data" method="post" action="/upload">
    文件:<input type="file" name="himg"/><p/>
    姓名:<input type="text" name="name"/><p/>
    <input type="submit" value="上传"/>
</form>

 (3)控制器UploadController 处理业务

@RestController
public class UploadController {

    //绝对路径
    private static final String filePath = "D:\\javalesson\\demoboot1\\src\\main\\resources\\static\\images\\";

    @PostMapping("/upload")
    public JsonData upload(@RequestParam("himg") MultipartFile file, HttpServletRequest request) {

        //图片大小进行判断
//        file.getSize()
        //图片是否为空
        if (!file.isEmpty()) {
            //获取文件名
            String name = request.getParameter("name");
            System.out.println(name);

            // 获取文件名
            String fileName = file.getOriginalFilename();
            System.out.println("上传的文件名为:" + fileName);

//            获取后缀名 如:jpg,png
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            System.out.println(suffixName);

            //拼接路径
            File destPath = new File(filePath + fileName);
            System.out.println(destPath);

            try {
                //文件保存
                file.transferTo(destPath);
                return new JsonData(0, "上传成功", fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new JsonData(-1, "上传失败!", fileName);
        }
        return new JsonData(-1, "上传失败!", null);

    }
}

(4)运行 http://localhost:8080/upload.html

 

查看目录路径:

 http://localhost:8080/images/girl.png

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值