Springboot前后端分离实现文件上传

Springboot前后端分离实现文件上传

文件上传

文件上传是项目经常要用到的功能,Springboot可以通过配置MultipartFile 来接受文件。 项目采用的是前后端分离的模式,springboot+vue,也可以通过这种方式来实现。

代码实现

controller层代码

实现一 通过二进制流转化为file

@ApiOperation(value = "文件上传")
    @PostMapping(value = "/upload")
    @CrossOrigin
    public String fileUpload(
             MultipartFile file) {
          
   
        try {
          
   
            byte[] bytes = file.getBytes();
            Path path = Paths.get("C:\upload\"+file.getOriginalFilename());
            Files.write(path,bytes);
            return "文件上传成功";
        } catch (IOException e) {
          
   
            e.printStackTrace();
            return "文件上传失败";
        }
    }

实现二 通过MultipartFile 的transferTo方法转成file

@ApiOperation(value = "文件上传")
    @PostMapping(value = "/upload")
    @CrossOrigin
    public String fileUpload(
             MultipartFile file) {
          
   
        try {
          
   
        	String name = file.getOriginalFilename() == null ? "" : file.getOriginalFilename();
        	String path = FileUtil.getTmpPath(Enums.TmpPath.UPLOAD.getCode()) + File.separator + name;
        	File uploadFile = new File(path);
            file.transferTo(uploadFile);
            return "文件上传成功";
        } catch (IOException e) {
          
   
            e.printStackTrace();
            return "文件上传失败";
        }
    }

通过PostMan调用刚才写好的文件上传接口 提示文件上传成功。

经验分享 程序员 微信小程序 职场和发展