Springboot整合 Minio

Springboot整合 Minio

1、添加依赖

       <dependency>
            <groupId>io.miniogroupId>
            <artifactId>minioartifactId>
            <version>7.0.2version>
        dependency>

2、添加配置

# 自定义配置项,方便在代码中使用
minio:
  endpoint: 192.168.31.129
  port: 9000
  accessKey: admin
  secretKey: 123456789
  bucketName: car

3、添加工具类

配置类

@Data
@Configuration
/*加载yml文件中以minio开头的配置项*/
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
    /*会自动的对应配置项中对应的key*/
    private String endpoint;//minio.endpoint
    private String accessKey;
    private String secretKey;
    private Integer port;
    /*把官方提供的MinioClient客户端注册到IOC容器中*/
    @Bean
    public MinioClient getMinioClient() throws InvalidEndpointException, InvalidPortException {
        MinioClient   minioClient = new MinioClient(getEndpoint(), getPort(), getAccessKey(), getSecretKey(), false);
        return minioClient;
    }
}

工具类:

@Component
public class MinioClientUtil {
    @Value("${minio.bucketName}")
    private String bucketName;
    @Autowired
    private io.minio.MinioClient minioClient;
    private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
    
    /**
     * 检查存储桶是否存在
     */
    public boolean bucketExists(String bucketName) throws InvalidKeyException, ErrorResponseException,
            IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException,
            InvalidResponseException, NoSuchAlgorithmException, XmlParserException, IOException {
        boolean flag = minioClient.bucketExists(this.bucketName);
        if (flag) return true;
        return false;
    }

    /**
     * 通过InputStream上传对象
     *
     * @param objectName 存储桶里的对象名称
     * @param stream     要上传的流 (文件的流)
     */
    public boolean putObject(String objectName, InputStream stream) throws Exception {

        //判断 桶是否存在
        boolean flag = bucketExists(bucketName);

        if (flag) {
            //往桶中添加数据   minioClient 进行添加

            /**
             *   参数1: 桶的名称
             *   参数2: 文件的名称
             *   参数3: 文件的流
             *   参数4: 添加的配置
             */
            minioClient.putObject(bucketName, objectName, stream, new PutObjectOptions(stream.available(), -1));
            ObjectStat statObject = statObject(objectName);
            if (statObject != null && statObject.length() > 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 删除一个对象
     * @param objectName 存储桶里的对象名称
     */
    public boolean removeObject(String objectName)throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            minioClient.removeObject(bucketName, objectName);
            return true;
        }
        return false;
    }
    /**
     * 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
     * @param objectNames 含有要删除的多个object名称的迭代器对象
     */
    public List<String> removeObject(List<String> objectNames) throws Exception {
        List<String> deleteErrorNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<DeleteError>> results = minioClient.removeObjects(bucketName, objectNames);
            for (Result<DeleteError> result : results) {
                DeleteError error = result.get();
                deleteErrorNames.add(error.objectName());
            }
        }
        return deleteErrorNames;
    }
    
    /**
     * 获取对象的元数据
     * @param objectName 存储桶里的对象名称
     */
    public ObjectStat statObject(String objectName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = minioClient.statObject(bucketName, objectName);
            return statObject;
        }
        return null;
    }
    /**
     * 文件访问路径
     * @param objectName 存储桶里的对象名称
     */
    public String getObjectUrl(String objectName) throws Exception {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            url = minioClient.getObjectUrl(bucketName, objectName);
        }
        return url;
    }
}

4、controller中的使用

    @Autowired
    private MinioClientUtil minioClientUtil;

    @PostMapping("/img")
    public Result uploadMinio(@RequestPart MultipartFile file) throws Exception {

        //拿到图片  MultipartFile封装接受的类
        //拿到图片的名称
        String filename = file.getOriginalFilename();

        //拿到图片的 UUId + 图片类型 (解决图片重名的问题 )
        String uuid = UUID.randomUUID().toString();
        String imgType = filename.substring(filename.lastIndexOf("."));

        //图片文件的新名称 xxx/uuid.jpg   图片拼接后的名
        String fileName = uuid + imgType;

        boolean flag = minioClientUtil.putObject(fileName, file.getInputStream());


        String path = "http://192.168.31.129:9000/car/" + fileName;

        return flag ? Result.ok("上传成功",path):Result.fail("图片删除失败");
    }

5、前端的组件

1、添加样式

    

2、添加组件


    <el-dialog title="车辆类型添加" :visible.sync="dialogFormADDVisible">
        <el-form :model="addCarType">
            <el-form-item label="车辆类型名称" label-width="240px">
                <el-input v-model="addCarType.typeName" autocomplete="off">el-input>
            el-form-item>

            <el-form-item label="车辆公司" label-width="240px">
                <el-input v-model="carType.company" autocomplete="off">el-input>
            el-form-item>

            
            <el-form-item label="汽车图片" label-width="240px">

                <el-upload
                        class="avatar-uploader"
                        action="http://localhost:9000/img"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon">i>
                el-upload>

            el-form-item>


            <el-form-item label="备注" label-width="240px">
                <el-input v-model="addCarType.remarks" autocomplete="off">el-input>
            el-form-item>

        el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormADDVisible = false">取 消el-button>
            <el-button type="primary" @click="commitADDCarType">确 定el-button>
        div>
    el-dialog>

3、添加js

//图片上传成功的执行的函数
handleAvatarSuccess(resp, file){
    console.log(resp)
    console.log(resp.data);

    //上传成功的图片回显
    this.imageUrl = resp.data;
},

    //添加显示
    showAddDialog(){
        this.dialogFormADDVisible = true;
    }

你可能感兴趣的:(spring,boot,java,spring)