15 springboot实现图片上传

使用springboot上传文件是非常容易的,但是里面也有坑,请注意哦

方法1://创建文件目录,和文件目录+文件分开的

/** 
     * @Description:  图片上传
     * @Author: duanweijie
     * @Date: 2020/5/12
     */
    @RequestMapping("/upload")
    public String upload(MultipartFile file){
  //方法1
String path="E:/file/temp";

String targetPath=path+"/"+file.getOriginalFilename(); //这个是文件的路径

File filePath = new File(path); //这个是存放文件的目录

while (!filePath.exists()){
filePath.mkdirs();
}

try {
file.transferTo(new File(targetPath)); //注意此时的filePath是目标文件夹+文件名字,切记!!不要只搞成目标文件夹了
} catch (Exception e) {
e.printStackTrace();
}

return "ok";
 }

方法二://创建文件目录,和文件目录+使用同一个

@PostMapping("/upload")
    public String test(MultipartFile file){



        String fileName=file.getOriginalFilename();
        String path="E:/file/temp";
        String targetPath=path+"/"+fileName;
        File filePath = new File(targetPath);

    //注意是创建存放路径,不带文件名的那个路径
        System.out.println(filePath.getParentFile());
        while (!filePath.getParentFile().exists()){
            filePath.getParentFile().mkdirs();
        }

        try {
            file.transferTo(filePath); //注意此时的filePath是目标文件夹+文件名字,切记!!不要只搞成目标文件夹了
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "ok";
    }    

postman测试

 结果

 至此,ok

原文地址:https://www.cnblogs.com/gfbzs/p/12878819.html