Spring Boot 文件上传

  1. @RequestParam(“file”) MultipartFile file
    将请求参数绑定到你控制器的方法参数上 file是指前端上传input的name的值
  2. MultipartFile 类
    用来接收前端传来的文件
  3. ResourceUtils类
    ResourceUtils 工具类,支持“classpath:”和“file:”的地址前缀,能够从指定的地址加载文件资源
    通过ResourceUtils.getURL(“classpath:”).getPath()可以获取到路径
方法区别
getPath()获取file的路径,如果默认为相对路径则返回相对路径
getAbsolutePath()获取全路径,如果构造的时候试相对路径,返回当前目录的路径+构造file时候的路径
  1. 根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
File(String parent, String child) 
  1. transferTo()方法
    因为文件流只可以接收读取一次,传输完毕则关闭流;
    在文件上传的时候,MultipartFile中的transferTo(dest)方法只能使用一次;
    并且使用transferTo方法之后不可以在使用getInputStream()方法;
    否则再使用getInputStream()方法会报异常
    使用transferTo(dest)方法将上传文件写到服务器上指定的文件;

controller类:

@PostMapping("/product/upload")
public Result upload(@RequestParam("file") MultipartFile file){
    try {
        File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
        System.out.println("地址:"+projectPath);
        File upload = new File(projectPath.getAbsolutePath(),"static/img/product");
        if(!upload.exists()){
            upload.mkdirs();
        }
        Result result = null;
        if(file.isEmpty()){
            result = ResultUtils.error(-1,"上传失败");
        }
        String fileName = file.getOriginalFilename();

        File dest = new File(upload.getAbsolutePath()+File.separator+fileName);


    file.transferTo(dest);

    Map<String,String> map=new HashMap<String,String>();
    map.put("src",fileName);
    result = ResultUtils.success(map);
    result.setCode(0);
}catch (Exception e){

}
return ResultUtils.error(-1,"上传失败");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值