zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    WCF和SOA的简介
    .NET 反射应用
    ASP.NET---如何使用web api创建web服务
    获得N位数字字母随机组合
    git的初步使用
    js贪吃蛇
    python多线程
    2013-12-13
    2012-12-12
    2013-12-5
  • 原文地址:https://www.cnblogs.com/gfbzs/p/12878819.html
Copyright © 2011-2022 走看看