目前已经实现本地存储、Minio云存储、阿里云、腾讯云、七牛云、华为云等文件存储服务。

公共配置

下面是文件存储的公共配置信息,具体含义如下:

  • storage.enabled 是否开启存储服务
  • storage.config.type 存储类型,可选值【local、minio、aliyun、tencent、qiniu、huawei】
  • storage.config.domain 访问域名,具体可以在第三方云服务里面配置,或者使用云服务提供的免费域名。如果是local,则为后端服务器地址。
  • storage.config.prefix 文件上传前缀,如:前缀为images,则访问路径会自动追加images前缀
storage:
  enabled: true
  config:
    type: local
    domain: http://localhost:8080
    prefix: 

API接口

引入组件后,我们就可以在程序里面调用,下面是存储API接口,如下所示:

/**
 * 存储服务API
 *
 * @author 阿沐 babamu@126.com
 */
public interface StorageApi {

    /**
     * 根据文件名,生成带时间戳的新文件名
     *
     * @param fileName 文件名
     * @return 返回带时间戳的文件名
     */
    String getNewFileName(String fileName);

    /**
     * 生成路径,不包含文件名
     *
     * @return 返回生成的路径
     */
    String getPath();

    /**
     * 根据文件名,生成路径
     *
     * @param fileName 文件名
     * @return 生成文件路径
     */
    String getPath(String fileName);

    /**
     * 文件上传
     *
     * @param data 文件字节数组
     * @param path 文件路径,包含文件名
     * @return 返回http地址
     */
    String upload(byte[] data, String path);

    /**
     * 文件上传
     *
     * @param inputStream 字节流
     * @param path        文件路径,包含文件名
     * @return 返回http地址
     */
    String upload(InputStream inputStream, String path);
}

API接口调用

下面提供了调用API接口的DEMO,如下所示:

@Service
@AllArgsConstructor
public class FileUploadService {
    private final StorageApi storageApi;

    public void upload(MultipartFile file) {
        String path = storageApi.getPath(file.getOriginalFilename());
        String url = storageApi.upload(file.getBytes(), path);
    }
}