Java使用MinIO进行文件的上传、下载和删除

Minio Java Client使用

MinIO Java Client SDK提供简单的API来访问任何与Amazon S3兼容的对象存储服务。

官方文档:https://min.io/docs/minio/linux/developers/java/API.html

Spring项目

引入依赖

<dependency> 
  <groupId>io.minio</groupId> 
  <artifactId>minio</artifactId> 
  <version>8.3.0</version> 
</dependency>

<dependency> 
  <groupId>me.tongfei</groupId> 
  <artifactId>progressbar</artifactId> 
  <version>0.5.3</version> 
</dependency>

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>4.8.1</version> 
</dependency>

文件上传

public class FileUploader {
    public static void main(String[] args)
            throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        try {

            // Create a minioClient with the MinIO server playground, its access key and secret key.

            MinioClient minioClient = MinioClient.builder().endpoint("http://192.168.3.14:9000").credentials("admin", "12345678").build();

            // 创建bucket

            String bucketName = "tulingmall";

            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) { // 不存在,创建bucket
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); 
            } 
            // 上传文件 
            minioClient.uploadObject( UploadObjectArgs.builder()
                                                    .bucket(bucketName)
                                                    .object("tuling-mall-master.zip")
                                                    .filename("F:\\mall\\tuling-mall-master.zip")
                                                    .build()
            );
            System.out.println("上传文件成功"); 
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace()); 
        }
    }
}

文件下载

public class DownLoadDemo {

    public static void main(String[] args) {

        // Create a minioClient with the MinIO server playground, its access key and secret key.

        MinioClient minioClient = MinioClient.builder().endpoint("http://192.168.3.14:9000").credentials("admin", "12345678").build();

        // Download object given the bucket, object name and output file name 
        try {
            minioClient.downloadObject( DownloadObjectArgs.builder()
                    .bucket("tulingmall")
                    .object("fox/fox.jpg")
                    .filename("fox.jpg")
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

SpringBoot项目

构建MinioClient对象,并交给spring管理

@Data 
@Component 
@ConfigurationProperties(prefix = "minio") 
public class MinioProperties { 
    private String endpoint; 
    private String accessKey; 
    private String secretKey;

}

yml文件添加相关配置信息

minio:
	endpoint: http://192.168.3.14:9000 
	accesskey: admin 
  secretKey: 12345678

创建Minio配置类

@Configuration 
public class MinioConfig {

    @Autowired 
    private MinioProperties minioProperties;

    @Bean 
    public MinioClient minioClient(){ 
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();
        return minioClient;
    }
}

进行文件的上传、下载和删除

@RestController 
@Slf4j 
public class MinioController {

    @Autowired 
    private MinioClient minioClient;

    @Value("${minio.bucketName}") 
    private String bucketName;

    @GetMapping("/list") 
    public List<Object> list() throws Exception { 
        
        //获取bucket列表
        Iterable<Result<Item>> myObjects = minioClient.listObjects(
                ListObjectsArgs.builder()
                        .bucket(bucketName)
                        .build()
        );
        
        Iterator<Result<Item>> iterator = myObjects.iterator();
        List<Object> items = new ArrayList<>();
        String format = "{'fileName':'%s','fileSize':'%s'}";
        while (iterator.hasNext()) { 
            Item item = iterator.next().get();
            items.add(
                    JSON.parse(String.format(
                            format, item.objectName(), 
                            formatFileSize(item.size())
                        )
                    )
            ); 
        }
        return items; 
    }

    @PostMapping("/upload") 
    public Res upload(@RequestParam(name = "file", required = false) MultipartFile[] file) {

        if (file == null || file.length == 0) {
            return Res.error("上传文件不能为空"); 
        }

        List<String> orgfileNameList = new ArrayList<>(file.length);

        for (MultipartFile multipartFile : file) {

            String orgfileName = multipartFile.getOriginalFilename(); 
            orgfileNameList.add(orgfileName); 
            try {

                //文件上传
                InputStream in = multipartFile.getInputStream();
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucketName)
                                .object(orgfileName)
                                .stream(in, multipartFile.getSize(), -1)
                                .contentType(multipartFile.getContentType())
                                .build()); 
                in.close();
            } catch (Exception e) { 
                log.error(e.getMessage()); 
                return Res.error("上传失败");
            }

        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("bucketName", bucketName); 
        data.put("fileName", orgfileNameList); 
        return Res.ok("上传成功",data);
    }

    @RequestMapping("/download/{fileName}") 
    public void download(HttpServletResponse response, @PathVariable("fileName") String fileName) {

        InputStream in = null; 
        try {

            // 获取对象信息 
            StatObjectResponse stat = minioClient.statObject(
                    StatObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .build()
            ); 
            response.setContentType(stat.contentType());
            response.setHeader(
                    "Content-Disposition", 
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")
            );

            //文件下载 
            in = minioClient.getObject( 
                    GetObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );

            IOUtils.copy(
                    in, 
                    response.getOutputStream()
            ); 
        } catch (Exception e) {
            log.error(e.getMessage()); 
        } finally {
            if (in != null) {
                try { 
                    in.close();
                } catch (IOException e) { 
                    log.error(e.getMessage());
                }
            }
        }
    }

    @DeleteMapping("/delete/{fileName}") 
    public Res delete(@PathVariable("fileName") String fileName) {

        try {
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );
        } catch (Exception e) { 
            log.error(e.getMessage()); 
            return Res.error("删除失败");
        }
        return Res.ok("删除成功",null);
    }

    private static String formatFileSize(long fileS) {

        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = ""; 
        String wrongSize = "0B"; 
        if (fileS == 0) {

            return wrongSize; 
        } if (fileS < 1024) {

            fileSizeString = df.format((double) fileS) + " B"; 
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + " KB"; 
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + " MB"; 
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + " GB"; 
        } 
        return fileSizeString;
    }
}
  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java使用Minio存储文件可以通过Minio提供的Java SDK来实现。Minio是一个开源的分布式对象存储服务,可以用于存储和检索大量的数据,同时也支持并发上传下载、合并、删除等操作。下面是一个使用Minio存储文件的示例代码: 1. 首先需要引入MinioJava SDK依赖: ``` <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>RELEASE.2021-06-17T22-56-34Z</version> </dependency> ``` 2. 创建Minio客户端并连接到Minio服务器: ``` String endpoint = "http://minio.example.com"; String accessKey = "ACCESS_KEY"; String secretKey = "SECRET_KEY"; MinioClient minioClient = new MinioClient.Builder() .endpoint(endpoint) .credentials(accessKey, secretKey) .build(); ``` 3. 创建一个存储桶(Bucket): ``` String bucketName = "java.minio.demo"; boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build()); if (!bucketExists) { minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); } ``` 4. 上传文件Minio服务器: ``` File file = new File("D:\DownUpLoadTempFiles\100元.jpg"); InputStream inputStream = new FileInputStream(file); String objectName = "100元.jpg"; minioClient.putObject(PutObjectArgs.builder() .bucket(bucketName) .object(objectName) .stream(inputStream, inputStream.available(), -1) .build()); ``` 5. 下载文件: ``` String objectName = "100元.jpg"; File file = new File("D:\DownUpLoadTempFiles\100元.jpg"); minioClient.downloadObject(DownloadObjectArgs.builder() .bucket(bucketName) .object(objectName) .filename(file.getAbsolutePath()) .build()); ``` 6. 删除文件: ``` String objectName = "100元.jpg"; minioClient.removeObject(RemoveObjectArgs.builder() .bucket(bucketName) .object(objectName) .build()); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值