栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 调用 minio

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 调用 minio

pom 文件 添加依赖


    io.minio
    minio
    8.2.1

如果使用 8.3后的版本会报错

The following method did not exist:
okhttp3.RequestBody.create([BLokhttp3/MediaType;)Lokhttp3/RequestBody;
The calling method’s class, io.minio.S3Base, was loaded from the following location

原因是需要自行添加 okhttp 依赖


    io.minio
    minio
    8.4.1



    com.squareup.okhttp3
    okhttp
    4.9.3

application.yml 添加 minio 配置
注意:这里的 url 是 映射 minio 9000 端口的域名,accessKey 和 secretKey 在 Service Accounts 那一步创建

s3:
  url: "http://shareminio.saas.api.gd-xxx.com"
  accessKey: "zNsFa5x60rWKp4KK"
  secretKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"

配置 StorageProperty

@Data
@ConfigurationProperties(prefix = "s3")
public class StorageProperty {
    private String url;
    private String accessKey;
    private String secretKey;
    private long callTimeOut = 60000;
    private long readTimeOut = 300000;
}

配置 MinioClientConfig

@Configuration
public class MinioClientConfig {

    @Autowired
    private StorageProperty storageProperty;

    @Bean
    public OkHttpClient httpClient() {
        OkHttpClientFactory okHttpClientFactory = new DefaultOkHttpClientFactory(new OkHttpClient().newBuilder());
        return okHttpClientFactory.createBuilder(true)
                .retryOnConnectionFailure(true)
                .callTimeout(storageProperty.getCallTimeOut(), TimeUnit.MILLISECONDS)
                .readTimeout(storageProperty.getReadTimeOut(), TimeUnit.MILLISECONDS)
                .build();
    }
    
    @Bean(name = {"minioClient"})
    public MinioClient minioClient() {
        OkHttpClient client = httpClient();
        return MinioClient
                .builder().httpClient(client)
                .endpoint(storageProperty.getUrl())
                .credentials(storageProperty.getAccessKey(), storageProperty.getSecretKey())
                .build();
    }
}

minio 上传

public void upload(String repository, String path, String fileName, MultipartFile file) throws Exception {
    minioClient.putObject(PutObjectArgs.builder()
       .bucket(repository)
       .object(path + fileName)
       .stream(file.getInputStream(), file.getSize(), -1)
       .build());
}

minio 下载,获取文件流

public InputStream download(String repository, String path, String fileName) {
   try {
       InputStream inputStream =
               minioClient.getObject(GetObjectArgs.builder().bucket(repository).object(path + fileName).build());
       return inputStream;
   } catch (Exception e) {
       e.printStackTrace();
       throw new BaseException("DOWNLOAD_FROM_MINIO_FAILED", "下载出错!", e);
   }
}

minio 下载,获取 url

 
public String getDownloadUrl(String repository, String path, String fileName, int expireSeconrd) {
    try {
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .expiry(expireSeconrd)
                .method(Method.GET)
                .bucket(repository)
                .object(path + fileName).build());
    } catch (Exception e) {
        throw new BaseException("GET_DOWNLOAD_URL_ERROR", "获取下载链接错误!", e);
    }
}

minio 复制文件

 
public String copy(String repository, String path, String fileName, String srcRepository, String srcPath,
                   String srcFileName) {
    try {
        ObjectWriteResponse writeResponse = minioClient.copyObject(CopyObjectArgs.builder()
                .source(CopySource.builder().bucket(srcRepository).object(srcPath + srcFileName).build())
                .bucket(repository)
                .object(path + fileName).build());
        return writeResponse.etag();
    } catch (Exception e) {
        throw new BaseException("COPY_TO_MINIO_FAILED", "上传至Minio出错!", e);
    }
}

minio 删除文件

public void remove(String repository, String path, String fileName) {
    try {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(repository).object(path + fileName).build());
    } catch (Exception e) {
        throw new BaseException("REMOVE_FROM_MINIO_FAILED", "删除Minio文件出错!", e);
    }
}

minio 获取 StatObjectResponse

    public StatObjectResponse getObjectStat(String repository, String path, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        return minioClient.statObject(StatObjectArgs.builder().bucket(repository).object(path + fileName).build()
        );
    }

controller 上传示例

    @ApiOperation(value = "minio", notes = "使用原文件名,相同文件名会覆盖")
    @PostMapping(value = "/minio")
    NjcResponseEntity uploadFile(MultipartFile file) throws Exception {
        storageService.upload(REPOSITORY, "/fat1/", file.getOriginalFilename(), file);
        return super.success("插入成功");
    }

自动生成 /fat1 文件夹,注意:相同文件名会覆盖

controller 下载示例

 @ApiOperation(value = "minio", notes = "获取文件流")
 @GetMapping(value = "/minio")
 void downloadStream(@RequestParam(value = "name") String name,HttpServletResponse response) throws Exception {
     try {
         InputStream inputStream = storageService.download(REPOSITORY,"/", name);
         StatObjectResponse objectStat = storageService.getObjectStat(REPOSITORY,"/", name);

         response.setContentType(objectStat.contentType());
         response.setCharacterEncoding("UTF-8");
         response.setHeader("Content-Disposition",
                 "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));

         IOUtils.copy(inputStream, response.getOutputStream());
         inputStream.close();
     } catch (BaseException bd) {
         log.error("BaseException:", bd);
         response.sendError(500, bd.getMessage());
     }
 }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/962343.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号