博主
258
258
258
258
专辑

第四节 文件上传工具类

亮子 2022-06-23 14:28:26 2819 0 0 0

1、工具类代码

package com.shenmazong.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 军哥
 * @version 1.0
 * @description: 文件上传工具类
 * @date 2022/1/13 17:49
 */

public class FileUploadUtil {

    private String uploadDir = "/files";
    private String fileUrl = null;
    private String fileName = null;
    private long fileSize = 0L;
    private String domain = "";

    private FileUploadUtil() {

    }

    public static FileUploadUtil upload() {
        return new FileUploadUtil();
    }

    /**
     * @description 设置上传文件的存储路径
     * @author 军哥
     * @date 2022/1/17 14:31
     * @version 1.0
     */
    public FileUploadUtil setUploadDir(String dir) {
        this.uploadDir = dir;

        return this;
    }

    /**
     * @description 设置全路径URL的域名
     * @author 军哥
     * @date 2022/1/17 14:31
     * @version 1.0
     */
    public FileUploadUtil setDomain(String domain) {
        this.domain = domain;
        return this;
    }

    public String saveFile(MultipartFile file) {
        if(file.isEmpty()){
            return null;
        }

        //-- 获取上传的文件名
        String fileName = file.getOriginalFilename();
        this.fileSize = file.getSize();

        //-- 使用随机文件名,防止文件覆盖
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String newName = UUID.randomUUID().toString();
        newName = newName + suffix;

        File dest = new File(uploadDir + "/" + newName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        try {
            // 保存文件
            file.transferTo(dest);

            // 返回上传的文件信息
            this.fileUrl = newName;
            this.fileName = fileName;
            return newName;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }



    public String getFileName() {
        return this.fileName;
    }

    public String getFileUrl() {
        return this.domain + this.fileUrl;
    }

    public long getFileSize() {
        return this.fileSize;
    }
}

2、工具类使用

    @ApiOperation(value="商家上传LOGO", notes="商家上传LOGO", produces="application/json")
    @PostMapping("/logoUpload")
    public ResultResponse logoUpload(@RequestParam("file") MultipartFile file){
        // 设置文件上传配置
        FileUploadUtil uploadUtil = FileUploadUtil.upload()
                .setDomain("http://localhost:8040/user/img/")
                .setUploadDir("E:/var/images");

        // 文件上传
        String fileUrl = uploadUtil.saveFile(file);
        if(fileUrl == null) {
            return ResultResponse.FAILED(505, "文件上传失败");
        }

        // 获取上传文件信息
        HashMap<String, String> map = new HashMap<>();
        map.put("name", uploadUtil.getFileName());
        map.put("url", uploadUtil.getFileUrl());

        return ResultResponse.SUCCESS(map);
    }

3、图片文件回显

方法一:修改配置文件

  • 修改application.properties文件
# resource
spring.resources.static-locations=classpath:/static/,file:E:\\opt\\img\\
spring.mvc.static-path-pattern=/img/**
  • 修改application.yml文件
spring:
  resources:
    static-locations: classpath:/static/,file:D:\\img\\

方法二:使用配置类

@Slf4j
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    private final String UPLOAD_DIR = "E:/test";


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String location = "file:///" + UPLOAD_DIR;
        log.info("localtion:"+location);

        registry.addResourceHandler("/storage/thumbnails/**")
                .addResourceLocations(location + "/storage/thumbnails/");
    }
}