Springboot上传文件本地

2020-04-08  本文已影响0人  白云的离殇

1.在application中定义文件上传目录以及映射

project:
  ##win上传地址
  winpath: F:\common\upload\
  ##mac/linux上传地址
  otherospath: /Users/sdl/upload/
  ##映射地址
  profile: /profile/**

2.新建配置类,将数据注入

/**
 * @author sdl
 * @date 2020/4/8 3:32 下午
 * @description 项目配置
 */
@Component
@ConfigurationProperties(prefix = "project")
public class ProjectConfig {
    static String winpath;
    static String otherospath;
    static String profile;
    public String getWinpath() {
        return winpath;
    }

    public void setWinpath(String winpath) {
        this.winpath = winpath;
    }

    public String getOtherospath() {
        return otherospath;
    }

    public void setOtherospath(String otherospath) {
        this.otherospath = otherospath;
    }

    public static String getProfile() {
        return profile;
    }

    public void setProfile(String profile) {
        this.profile = profile;
    }

    public static String getPath(){
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            return winpath;
        }else {
            return otherospath;
        }
    }
}

3.新建web配置类,添加地址映射。这样就能在项目中用映射地址访问文件绝对路径。

/**
 * @author sdl
 * @date 2020/4/8 2:16 下午
 * @description Web配置
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 映射文件地址
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(ProjectConfig.getProfile()).addResourceLocations("file:"+ProjectConfig.getPath());
    }
}

4.新建上传工具类

package com.sdl.elm.utils;

import com.sdl.elm.config.ProjectConfig;
import com.sdl.elm.config.ServerConfig;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author sdl
 * @date 2020/4/7 5:26 下午
 * @description
 */
public class FieUtil {
    /**
     * Java文件操作 获取不带扩展名的文件名
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }
    /**
     * 获取文件扩展名,不带 .
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
    /**
     * 将绝对路径转换项目路径
     */
    public static String getperfilename(String path){
        String suffix = path.substring(ProjectConfig.getPath().length());
        String prefix = ServerConfig.getUrl() + ProjectConfig.getProfile().substring(0,ProjectConfig.getProfile().length()-2);
        return prefix+suffix;
    }
    /**
     * 上传文件
     * @param file 文件
     * @param filePath 路径
     * @return 返回项目路径
     */
    public static String upload(MultipartFile file, String filePath) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS");
        String name = getFileNameNoEx(file.getOriginalFilename());
        String suffix = getExtensionName(file.getOriginalFilename());
        String nowStr = "-" + format.format(date);
        try {
            String fileName = name + nowStr + "." + suffix;
            String path = filePath + fileName;
            // getCanonicalFile 可解析正确各种路径
            File dest = new File(path).getCanonicalFile();
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 文件写入
            file.transferTo(dest);
            return getperfilename(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath)
    {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
            file.delete();
            flag = true;
        }
        return flag;
    }
}

5.测试,新建uploadcontroller。

/**
 * @author sdl
 * @date 2020/4/8 10:12 下午
 * @description
 */
@RestController
public class UploadController {
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
       if(!file.isEmpty()){
           String url = FileUtil.upload(file, ProjectConfig.getPath());
           return Result.success("上传成功!",url);
       }else {
           return Result.error("error");
       }
    }
}

6.使用postman测试接口,注意在header里添加 Content-Type:multipart/form-data


header参数

上传成功,返回链接可直接打开


结果
返回链接
上一篇 下一篇

猜你喜欢

热点阅读