使用minio实现文件上传、文件下载

1、导入minio依赖:

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

2、application.yml添加配置

# MinIo文件服务器
minio:
  # bucket名称
  bucket: "test"
  # Minio服务地址
  host: "http://192.168.137.1:9000"
  # 访问路径
  url: "${minio.host}/${minio.bucket}/"
  # MINIO_ACCESS_KEY
  access-key: "minioadmin"
  # MINIO_SECRET_KEY
  secret-key: "minioadmin"

3、编写帮助类:

package com.hdyanfa.interact.config;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Component
public class MinioHelper {

    @Value(value = "${minio.bucket}")
    private String bucket;

    @Value(value = "${minio.host}")
    private String host;

    @Value(value = "${minio.url}")
    private String url;

    @Value(value = "${minio.access-key}")
    private String accessKey;

    @Value(value = "${minio.secret-key}")
    private String secretKey;

    //minio上传文件
    public String putObject(MultipartFile multipartFile) throws InvalidEndpointException, InvalidPortException,
            IOException, InvalidKeyException, ErrorResponseException, IllegalArgumentException,
            InsufficientDataException, InternalException, InvalidBucketNameException, InvalidResponseException,
            NoSuchAlgorithmException, XmlParserException, RegionConflictException {

        MinioClient minioClient = new MinioClient(this.host, this.accessKey, this.secretKey);

        // bucket 不存在,创建
        if (!minioClient.bucketExists(this.bucket)) {
            minioClient.makeBucket(this.bucket);
        }
        try (InputStream inputStream = multipartFile.getInputStream()) {

            // 上传文件的名称
            String fileName = multipartFile.getOriginalFilename();

            // PutObjectOptions,上传配置(文件大小,内存中文件分片大小)
            PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
            // 文件的ContentType
            putObjectOptions.setContentType(multipartFile.getContentType());
            minioClient.putObject(this.bucket, fileName, inputStream, putObjectOptions);

            // 返回访问路径
            return this.url + UriUtils.encode(fileName, StandardCharsets.UTF_8);
        }
    }

    //minio下载文件
    public void getObject(@RequestParam("filename") String filename, HttpServletResponse response){
        InputStream in = null;
        OutputStream out = null;
        try{
            MinioClient minioClient = new MinioClient(this.host, this.accessKey, this.secretKey);
            in=minioClient.getObject(bucket,filename);
            int length=0;
            byte[] buffer = new byte[1024];
            out = response.getOutputStream();
            response.reset();
            response.addHeader("Content-Disposition",
                    " attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.setContentType("application/octet-stream");
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (in != null){
                try {
                    in.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public MinioClient getMinioClient() throws InvalidPortException, InvalidEndpointException {
        MinioClient minioClient = new MinioClient(this.host, this.accessKey, this.secretKey);
        return minioClient;
    }
}

4、编写控制类

    private String saveAttachment1(MultipartFile multipartFile, int targetId, int targetType)  {
        // 附件上传并插入 "附件" 数据
        //获取上传的原始文件全称
        long length = multipartFile.getSize();
        //获取上传文件大小
        double fileSize = FileSizeUtil.getFileSize(length, "B");
        //如果上传文件大小大于100m
        if (fileSize / 1048576 > 100) {
            return "wrongFileSize";
        }
        String fileOriName = multipartFile.getOriginalFilename();
        //获取上传的文件名称
        String fileName = fileOriName.substring(0, fileOriName.lastIndexOf("."));
        String type = "jpg,png,jpeg,gif,txt,doc,docx,xls,xlsx,pdf,zip,rar";
        //获取上传文件的后缀名(文件类型)
        String fileExt = fileOriName.substring(fileOriName.lastIndexOf(".") + 1);
        //上传文件格式不符合
        if (!type.contains(fileExt)) {
            return "wrongFileType";
        }
        if(fileOriName.length()>100){
            return "filenameTooLong";
        }
        String size = String.valueOf(fileSize);



        String url=null;
        try{
            url=minioHelper.putObject(multipartFile);
        }catch (Exception e){
            e.printStackTrace();
        }

        //封装数据
        MessageAttachment attachment = new MessageAttachment();
        attachment.setTargetId(targetId);
        attachment.setTargetType(targetType);
        attachment.setOriginalName(fileOriName);
        attachment.setActualName(fileName);
        attachment.setFileSize(size);
        attachment.setFileUrl(url);
        attachment.setFileType(fileExt);
        attachmentService.save(attachment);
        return "success";
    }
5、在postman上测试

 文件上传、下载成功!

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值