通过Java实现Minio的文件上传与下载

1.导入依赖

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

2.application.yml 配置信息

minio:
  endpoint: http://127.0.0.1:9000 #minio地址
  accessKey: minioadmin #账号
  secretKey: minioadmin #密码
  bucketName: word-file #桶名称

3. MinioInfo实体类

@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioInfo {

    private String endpoint;

    private String accessKey;

    private String secretKey;
}

4.MinioConfig配置文件

@Configuration
@EnableConfigurationProperties(MinioInfo.class)
public class MinioConfig {
 
    @Autowired
    private MinioInfo minioInfo;
 
    /**
     * 获取 MinioClient
     */
    @Bean
    public MinioClient minioClient() throws NoSuchAlgorithmException, KeyManagementException {
        return MinioClient.builder()
                .endpoint(minioInfo.getEndpoint())
                .credentials(minioInfo.getAccessKey(),minioInfo.getSecretKey())
                .build();
   }

 

5.Minio工具类

@Slf4j
@Component
public class MinioUtils {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioInfo minioInfo;


    /**
     * 上传文件
     *
     * @param file
     * @param bucketName
     * @return
     * @throws Exception
     */
    public String uploadFile(MultipartFile file, String bucketName) {
        if (null == file || 0 == file.getSize()) {
            log.error("msg{}", "上传文件不能为空");
            return null;
        }
        try {
            // 判断是否存在
            createBucket(bucketName);
            // 原文件名
            String originalFilename = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName) // 桶名称
                            .object(originalFilename) // 文件存储名称
                            .stream(inputStream, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            inputStream.close();
            return minioInfo.getEndpoint() + "/" + bucketName + "/" + originalFilename;
        } catch (Exception e) {
            log.error("上传失败:{}", e.getMessage());
        }
        log.error("msg", "上传失败");
        return null;
    }


    /**
     * 通过字节流上传
     *
     * @param imageFullPath
     * @param bucketName
     * @param imageData
     * @return
     */
    public String uploadImage(String imageFullPath,
                              String bucketName,
                              byte[] imageData) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageData);
        try {
            // 判断是否存在
            createBucket(bucketName);
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(imageFullPath)
                    .stream(byteArrayInputStream, byteArrayInputStream.available(), -1)
                    .contentType(".jpg")
                    .build());
            return minioInfo.getEndpoint() + "/" + bucketName + "/" + imageFullPath;
        } catch (Exception e) {
            log.error("上传失败:{}", e.getMessage());
        }
        log.error("msg", "上传失败");
        return null;
    }

    /**
     * 删除文件
     *
     * @param bucketName
     * @param fileName
     * @return
     */
    public int removeFile(String bucketName, String fileName) {
        try {
            // 判断桶是否存在
            boolean res = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (res) {
                // 删除文件
                minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName)
                        .object(fileName).build());
            }
        } catch (Exception e) {
            System.out.println("删除文件失败");
            e.printStackTrace();
            return 1;
        }
        System.out.println("删除文件成功");
        return 0;
    }

    /**
     * 下载文件
     *
     * @param fileName
     * @param bucketName
     * @param response
     */
    public void fileDownload(String fileName,
                             String bucketName,
                             HttpServletResponse response) {

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            if (StringUtils.isBlank(fileName)) {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                String data = "文件下载失败";
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
                return;
            }
            outputStream = response.getOutputStream();
            // 获取文件对象
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            byte buf[] = new byte[1024];
            int length = 0;
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            // 输出文件
            while ((length = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            System.out.println("下载成功");
            inputStream.close();
        } catch (Throwable ex) {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            String data = "文件下载失败";
            try {
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            try {
                outputStream.close();
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    /**
     * 通过字节流下载
     * @param fileName 文件名称
     * @param bucketName 桶名称
     * @return
     */
    public byte[] byteDownload(String fileName,
                               String bucketName) {
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .build());
            byte[] buffer = StreamUtils.copyToByteArray(inputStream);
            inputStream.read(buffer);
            inputStream.close();
            return buffer;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @SneakyThrows
    public void createBucket(String bucketName) {
        // 如果不存在就创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }
}

6.Minio接口

@Slf4j
@RestController
public class MinioController {

    @Autowired
    private MinioUtils minioUtils;

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

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/v1/minio/upload")
    @ResponseBody
    public JSONObject uploadByMinio(@RequestParam(name = "file") MultipartFile file) {
        JSONObject jso = new JSONObject();
        String path = minioUtils.uploadFile(file, bucketName);
        jso.put("code", 2000);
        jso.put("data", path);
        jso.put("timestamp", new Date());
        return jso;
    }

    /**
     * 下载文件 根据文件名
     * @param fileName
     * @param response
     */
    @GetMapping("/v1/get/download")
    public void download(@RequestParam(name = "fileName") String fileName,
                         HttpServletResponse response){
        try {
            minioUtils.fileDownload(fileName,bucketName,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 下载文件 根据byte数组
     * @param
     */
    @GetMapping("/v1/get/downloadByte")
    public void downloadByte(String fileName){
        try {
            minioUtils.byteDownload(filePath,"word-file");
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    /**
     * 通过文件名删除文件
     * @param fileName
     * @return
     */
    @PostMapping("/v1/minio/delete")
    @ResponseBody
    public JSONObject deleteByName(String fileName){
        JSONObject jso = new JSONObject();
        int res = minioUtils.removeFile(bucketName, fileName);
        if (res!=0){
            jso.put("code",5000);
            jso.put("msg","删除失败");
        }
        jso.put("code",2000);
        jso.put("msg","删除成功");
        return jso;
    }
}

7.Postman实践操作

在Minio页面可以看到刚刚上传的文件

 

  • 11
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Minio是一个开源的分布式对象存储系统,它允许用户在存储服务上存储和检索数据。它支持S3 API,因此可以与大多数S3兼容的客户端和工具一起使用。 下面是使用Java实现Minio分片上传和下载文件的示例代码: ## 分片上传 ```java import io.minio.MinioClient; import io.minio.errors.MinioException; import io.minio.messages.Part; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; public class MinioUploader { private MinioClient minioClient; private final String bucketName; public MinioUploader(MinioClient minioClient, String bucketName) { this.minioClient = minioClient; this.bucketName = bucketName; } public void upload(String objectName, Path filePath) throws NoSuchAlgorithmException, IOException, MinioException { long fileSize = Files.size(filePath); long partSize = 5 * 1024 * 1024; // 5MB int partCount = (int) Math.ceil((double) fileSize / partSize); List<Part> parts = new ArrayList<>(); for (int i = 0; i < partCount; i++) { int partNumber = i + 1; long offset = i * partSize; long size = Math.min(partSize, fileSize - offset); InputStream inputStream = Files.newInputStream(filePath); inputStream.skip(offset); String uploadId = minioClient.initiateMultipartUpload(bucketName, objectName); Part part = minioClient.uploadPart(bucketName, objectName, uploadId, partNumber, inputStream, size); parts.add(part); } minioClient.completeMultipartUpload(bucketName, objectName, parts); } } ``` ## 分片下载 ```java import io.minio.MinioClient; import io.minio.errors.MinioException; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.security.NoSuchAlgorithmException; import java.util.List; public class MinioDownloader { private MinioClient minioClient; private final String bucketName; public MinioDownloader(MinioClient minioClient, String bucketName) { this.minioClient = minioClient; this.bucketName = bucketName; } public void download(String objectName, Path filePath) throws NoSuchAlgorithmException, IOException, MinioException { long partSize = 5 * 1024 * 1024; // 5MB List<io.minio.messages.Part> parts = minioClient.listObjectParts(bucketName, objectName, null).getParts(); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath.toFile()))) { for (io.minio.messages.Part part : parts) { InputStream inputStream = minioClient.getObject(bucketName, objectName, part.partNumber(), 0L, partSize); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } inputStream.close(); } } } } ``` 这是一个基本的示例,实际使用时需要根据具体需求进行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值