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

本文详细介绍了如何在SpringBoot应用中集成Minio,包括添加依赖、配置文件管理、创建Minio实体类、配置MinioClient,以及实现文件上传、下载和删除功能的示例代码和Postman实践操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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页面可以看到刚刚上传的文件

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值