文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

MinIO的安装与使用

2023-08-18 19:42

关注

2.1 下载MinIO

演示以官网下载二进制文件配置,下载地址见上方,,,,docker安装更简单哦~

#创建目录mkdir /usr/local/minio/cd /usr/local/minio/#下载并添加权限wget http://dl.minio.org.cn/server/minio/release/linux-amd64/minio#赋值权限chmod +x minio

2.2 启动MinIO

#创建数据目录,数据目录存储需要大点mkdir -p /home/data/minio#创建日志目录mkdir -p /home/data/minio/logtouch /home/data/minio/log/minio.log#前台启动minio./minio server /home/data/minio#后台启动minionohup ./minio server /home/data/minio > /home/data/minio/log/minio.log &# nohup端口自定义启动服务 指定文件存放路径 /home/data/minio 还有设置日志文件路径 /home/data/minio/log/minio.lognohup ./minio server --address :9000 --console-address :9001 /home/data/minio > /home/data/minio/log/minio.log 2>&1 &

–address :9000 --console-address :9001 是配置端口,默认minio端口是9000,如果9000端口被占用了,那就加上这一串配置,端口号的冒号之前不需要特意写出ip,当然如果你的ip的动态变化的,而不是静态的话,前边的ip不用写上,当然最好是用静态的ip

在这里插入图片描述

关闭防火墙
如果未关闭,输入以下命令:

systemctl stop firewalld

注意:如果不想关闭防火墙,需要开放ip端口9000和设置静态控制访问IP

访问:http://192.168.92.100:9000查看控制台
这里我们都使用的默认配置账号密码 minioadmin:minioadmin

在这里插入图片描述

2.3 修改配置

这里账号和密码都是用的默认的,如果我们要修改可以在环境变量里设置
修改环境变量

  1. 打开 /etc/profile 文件

    vim /etc/profile
  2. 在文件的最末尾加上以下信息(启动的时候看提示,新版本需要用MINIO_ROOT_USERMINIO_ROOT_PASSWORD,旧版需要用MINIO_ACCESS_KEYMINIO_SECRET_KEY)。
    在这里插入图片描述
    按 i 键后,在文档末尾输入
    (1)新版:

    export MINIO_ROOT_USER=minioadminexport MINIO_ROOT_PASSWORD=admin123

    (2)旧版

    export MINIO_ACCESS_KEY=minioadminexport MINIO_SECRET_KEY=admin123
  3. 保存退出,刷新重载环境变量

    source /etc/profile

2.4 编写启动脚本,以及加入到systemctl中

为了方便管理,我们这里给命令添加到脚本中

  1. /usr/local/minio/目录下新建run.sh

    vim run.sh
  2. 然后将以下内容保存到run.sh,并为其赋予执行权限chmod +x run.sh

    #!/bin/bash#配置登陆账号密码export MINIO_ROOT_USER=minioadminexport MINIO_ROOT_PASSWORD=admin123# nohup启动服务 指定文件存放路径 /home/data/minio 还有设置日志文件路径 /home/data/minio/log/minio.lognohup ./minio server --address :9000 --console-address :9001 /home/data/minio > /home/data/minio/log/minio.log 2>&1 &
  3. 然后启动minio

    # 启动minio服务bash run.sh# 查看日志tail -200f /home/data/minio/log/minio.log

    在这里插入图片描述

    然后会有日志打印信息,然后可以看到minio服务器地址,和控制台信息地址

    然后在浏览器中访问地址http://192.168.92.100:9000,输入这个地址后会重定向到控制台登录地址http://192.168.92.100:9001/login

添加到systemctl启动命令中

  1. 编写minio.service文件

    vim /usr/lib/systemd/system/minio.service

    填写以下内容

    [Unit]Description=minioDocumentation=https://docs.min.ioWants=network-online.targetAfter=network-online.targetAssertFileIsExecutable=/usr/local/minio/minio[Service]#User and groupUser=rootGroup=rootExecStart=/usr/local/minio/run.sh#Let systemd restart this service alwaysRestart=always#Specifies the maximum file descriptor number that can be opened by this processLimitNOFILE=65536#Disable timeout logic and wait until process is stoppedTimeoutStopSec=infinitySendSIGKILL=no[Install]WantedBy=multi-user.target
  2. 赋值权限并且启动

    chmod +x /usr/lib/systemd/system/minio.service

    启动、查看、设置开机启动

    systemctl daemon-reloadsystemctl start miniosystemctl enable miniosystemctl status minio

    启动报错处理

    在这里插入图片描述

    systemctl start minioAssertion failed on job for minio.service.# 是 minio.service 的 AssertFileIsExecutable 路径错误AssertFileIsExecutable=/usr/local/minio# 改为AssertFileIsExecutable=/usr/local/minio/minio

到这里单机版的已经安装完毕!

3.1 项目应用

  1. 项目的pom文件中引入minio依赖
<properties>        <minio.version>7.1.0</minio.version> <dependencies>        <dependency>            <groupId>io.minio</groupId>            <artifactId>minio</artifactId>            <version>${minio.version}</version>        </dependency> </dependencies>
  1. application.yml文件中配置minio
minio:  endpoint: http://192.168.92.100  port: 9000  accessKey: minioadmin  secretKey: admin123  bucketName: test  secure: false spring:#设置文件上传大小限制  servlet:    multipart:      max-file-size: 100MB      max-request-size: 150MB
  1. 创建minio配置类和工具类
    配置类:
package cn.cvzhanshi.wechatpush.config;import io.minio.MinioClient;import io.minio.errors.InvalidPortException;import lombok.Getter;import lombok.Setter;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.stereotype.Component;@Configuration@Component@ConfigurationProperties(prefix = "minio")@Getter@Setterpublic class MinioConfig {    private String endpoint;    private int port;    private String accessKey;    private String secretKey;    private Boolean secure;    private String bucketName;    @Bean    public MinioClient getMinioClient() throws InvalidPortException {        MinioClient minioClient = MinioClient.builder().endpoint(endpoint, port, secure)                .credentials(accessKey, secretKey)                .build();        return minioClient;    }////    @Bean(name = "multipartResolver")//    public MultipartResolver multipartResolver(){//        CommonsMultipartResolver resolver = new CommonsMultipartResolver();//        resolver.setDefaultEncoding("UTF-8");//        //resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常//        resolver.setResolveLazily(true);//        resolver.setMaxInMemorySize(40960);//        //上传文件大小 50M 50*1024*1024//        resolver.setMaxUploadSize(50*1024*1024);//        return resolver;//    }}

工具类:

package cn.cvzhanshi.wechatpush.utils;import io.minio.*;import io.minio.errors.*;import io.minio.http.Method;import io.minio.messages.Bucket;import io.minio.messages.DeleteError;import io.minio.messages.DeleteObject;import io.minio.messages.Item;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.InputStream;import java.nio.charset.StandardCharsets;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.util.ArrayList;import java.util.List; @Component@Slf4jpublic class MinioClientUtils {     @Autowired    private MinioClient minioClient;     private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;         public boolean bucketExists(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = false;        flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());        if (flag) {            return true;        }        return false;    }         public boolean makeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, RegionConflictException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (!flag) {            minioClient.makeBucket(                    MakeBucketArgs.builder().bucket(bucketName).build());            return true;        } else {            return false;        }    }         public List<String> listBucketNames() throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        List<Bucket> bucketList = listBuckets();        List<String> bucketListName = new ArrayList<>();        for (Bucket bucket : bucketList) {            bucketListName.add(bucket.name());        }        return bucketListName;    }         public List<Bucket> listBuckets() throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        return minioClient.listBuckets();    }         public boolean removeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            Iterable<Result<Item>> myObjects = listObjects(bucketName);            for (Result<Item> result : myObjects) {                Item item = result.get();                // 有对象文件,则删除失败                if (item.size() > 0) {                    return false;                }            }            // 删除存储桶,注意,只有存储桶为空时才能删除成功。            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());            flag = bucketExists(bucketName);            if (!flag) {                return true;            }         }        return false;    }         public List<String> listObjectNames(String bucketName) throws XmlParserException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {        List<String> listObjectNames = new ArrayList<>();        boolean flag = bucketExists(bucketName);        if (flag) {            Iterable<Result<Item>> myObjects = listObjects(bucketName);            for (Result<Item> result : myObjects) {                Item item = result.get();                listObjectNames.add(item.objectName());            }        }        return listObjectNames;    }         public Iterable<Result<Item>> listObjects(String bucketName) throws XmlParserException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        if (flag) {            return minioClient.listObjects( ListObjectsArgs.builder().bucket(bucketName).build());        }        return null;    }         public boolean uploadObject(String bucketName, String objectName, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            minioClient.uploadObject(                    UploadObjectArgs.builder().bucket(bucketName).object(objectName).filename(fileName).build());            ObjectStat statObject = statObject(bucketName, objectName);            if (statObject != null && statObject.length() > 0) {                return true;            }        }        return false;     }         public void putObject(String bucketName, MultipartFile multipartFile, String filename) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);        putObjectOptions.setContentType(multipartFile.getContentType());        minioClient.putObject(                PutObjectArgs.builder().bucket(bucketName).object(filename).stream(                        multipartFile.getInputStream(), multipartFile.getSize(), -1).contentType(multipartFile.getContentType())                        .build());    }         public boolean putObject(String bucketName, String objectName, InputStream inputStream,String contentType) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        if (flag) {            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(                    //不清楚文件的大小时,可以传-1,10485760。如果知道大小也可以传入size,partsize。                    inputStream,  -1, 10485760)                    .contentType(contentType)                    .build());            ObjectStat statObject = statObject(bucketName, objectName);            if (statObject != null && statObject.length() > 0) {                return true;            }        }        return false;    }         public InputStream getObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            ObjectStat statObject = statObject(bucketName, objectName);            if (statObject != null && statObject.length() > 0) {                InputStream stream = minioClient.getObject( GetObjectArgs.builder()                        .bucket(bucketName)                        .object(objectName)                        .build());                return stream;            }        }        return null;    }         public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            ObjectStat statObject = statObject(bucketName, objectName);            if (statObject != null && statObject.length() > 0) {                InputStream stream = minioClient.getObject(  GetObjectArgs.builder()                        .bucket(bucketName)                        .object(objectName)                        .offset(1024L)                        .length(4096L)                        .build());                return stream;            }        }        return null;    }         public boolean downloadObject(String bucketName, String objectName, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            ObjectStat statObject = statObject(bucketName, objectName);            if (statObject != null && statObject.length() > 0) {                minioClient.downloadObject(DownloadObjectArgs.builder()                        .bucket(bucketName)                        .object(objectName)                        .filename(fileName)                        .build());                return true;            }        }        return false;    }         public boolean removeObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());            return true;        }        return false;    }         public List<String> removeObjects(String bucketName, List<DeleteObject> objectNames) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        List<String> deleteErrorNames = new ArrayList<>();        boolean flag = bucketExists(bucketName);        if (flag) {            Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(objectNames).build());            for (Result<DeleteError> result : results) {                DeleteError error = result.get();                deleteErrorNames.add(error.objectName());            }        }        return deleteErrorNames;    }         public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws InvalidExpiresRangeException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        String url = "";        if (flag) {            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {                throw new InvalidExpiresRangeException(expires,                        "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);            }            try {                url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()                        .method(Method.GET)                        .bucket(bucketName)                        .object(objectName)                        .expiry(expires)//动态参数                        //                       .expiry(24 * 60 * 60)//用秒来计算一天时间有效期//                        .expiry(1, TimeUnit.DAYS)//按天传参//                        .expiry(1, TimeUnit.HOURS)//按小时传参数                        .build());            } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidBucketNameException | InvalidExpiresRangeException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {                e.printStackTrace();            }        }        return url;    }         public String presignedPutObject(String bucketName, String objectName, Integer expires) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        String url = "";        if (flag) {            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {                try {                    throw new InvalidExpiresRangeException(expires,"expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);                } catch (InvalidExpiresRangeException e) {                    e.printStackTrace();                }            }            try {                url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()                        .method(Method.PUT)                        .bucket(bucketName)                        .object(objectName)                        .expiry(expires)//动态参数                        //                       .expiry(24 * 60 * 60)//用秒来计算一天时间有效期//                        .expiry(1, TimeUnit.DAYS)//按天传参//                        .expiry(1, TimeUnit.HOURS)//按小时传参数                        .build());            } catch (ErrorResponseException | InsufficientDataException e) {                e.printStackTrace();            } catch (InternalException e) {                log.error("InternalException",e);            } catch (InvalidBucketNameException e) {                log.error("InvalidBucketNameException",e);            } catch (InvalidExpiresRangeException e) {                log.error("InvalidExpiresRangeException",e);            } catch (InvalidKeyException e) {                log.error("InvalidKeyException",e);            } catch (InvalidResponseException e) {                log.error("InvalidResponseException",e);            } catch (IOException e) {                log.error("IOException",e);            } catch (NoSuchAlgorithmException e) {                log.error("NoSuchAlgorithmException",e);            } catch (ServerException e) {                log.error("ServerException",e);            } catch (XmlParserException e) {                log.error("XmlParserException",e);            }        }        return url;    }         public ObjectStat statObject(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        if (flag) {            ObjectStat statObject = null;            try {                statObject = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());            } catch (ErrorResponseException e) {                log.error("ErrorResponseException",e);            } catch (InsufficientDataException e) {                log.error("ErrorResponseException",e);                e.printStackTrace();            } catch (InternalException e) {                log.error("InternalException",e);            } catch (InvalidBucketNameException e) {                log.error("InvalidBucketNameException",e);            } catch (InvalidKeyException e) {                log.error("InvalidKeyException",e);            } catch (InvalidResponseException e) {                log.error("InvalidResponseException",e);            } catch (IOException e) {                log.error("IOException",e);            } catch (NoSuchAlgorithmException e) {                log.error("NoSuchAlgorithmException",e);            } catch (ServerException e) {                log.error("ServerException",e);            } catch (XmlParserException e) {                log.error("XmlParserException",e);            }            return statObject;        }        return null;    }         public String getObjectUrl(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        String url = "";        if (flag) {            try {                url = minioClient.getObjectUrl(bucketName, objectName);            } catch (ErrorResponseException e) {                log.error("XmlParserException",e);            } catch (InsufficientDataException e) {                log.error("InsufficientDataException",e);            } catch (InternalException e) {                log.error("InternalException",e);            } catch (InvalidBucketNameException e) {                log.error("InvalidBucketNameException",e);            } catch (InvalidKeyException e) {                log.error("InvalidKeyException",e);            } catch (InvalidResponseException e) {                log.error("InvalidResponseException",e);            } catch (IOException e) {                log.error("IOException",e);            } catch (NoSuchAlgorithmException e) {                log.error("NoSuchAlgorithmException",e);            } catch (ServerException e) {                log.error("ServerException",e);            } catch (XmlParserException e) {                log.error("XmlParserException",e);            }        }        return url;    }       public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {        try {             InputStream file = minioClient.getObject(GetObjectArgs.builder()                    .bucket(bucketName)                    .object(fileName)                    .build());            String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);            if (StringUtils.isNotEmpty(originalName)) {                fileName = originalName;            }            response.setHeader("Content-Disposition", "attachment;filename=" + filename);            ServletOutputStream servletOutputStream = response.getOutputStream();            int len;            byte[] buffer = new byte[1024];            while ((len = file.read(buffer)) > 0) {                servletOutputStream.write(buffer, 0, len);            }            servletOutputStream.flush();            file.close();            servletOutputStream.close();        } catch (ErrorResponseException e) {            log.error("ErrorResponseException",e);        } catch (Exception e) {            log.error("Exception",e);        }    }} 
  1. 创建一个数据表,用于保存上传到minio的文件的信息

    CREATE TABLE `minio_file` (  `id` bigint(20) NOT NULL COMMENT '文件id',  `original_file_name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '原始文件名称',  `file_ext_name` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件拓展名',  `file_size` bigint(20) DEFAULT NULL COMMENT '文件大小(单位:字节)',  `file_name` varchar(35) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '存入minio时的文件名称',  `mime` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件的content-type',  `file_url` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件路径',  `is_delete` tinyint(1) DEFAULT NULL COMMENT '是否删除 0 否 1 是',  `create_by` varchar(25) COLLATE utf8mb4_bin DEFAULT NULL,  `create_time` datetime DEFAULT NULL,  `update_by` varchar(25) COLLATE utf8mb4_bin DEFAULT NULL,  `update_time` datetime DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
  2. 创建minio上传接口

    package cn.cvzhanshi.wechatpush.controller;import cn.cvzhanshi.wechatpush.config.MinioConfig;import cn.cvzhanshi.wechatpush.utils.MinioClientUtils;import cn.hutool.core.io.FileUtil;import io.swagger.annotations.Api;import io.swagger.annotations.ApiImplicitParam;import io.swagger.annotations.ApiImplicitParams;import io.swagger.annotations.ApiOperation;import lombok.AllArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.RandomStringUtils;import org.apache.commons.lang3.math.NumberUtils;import org.springframework.stereotype.Controller;import org.springframework.util.CollectionUtils;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import java.io.FileInputStream;import java.time.Instant;import java.util.ArrayList;import java.util.List;@RestController@RequestMapping("/fileHandle")@Slf4j@AllArgsConstructor@Api(tags = "文件处理模块")public class FileHandleController {private MinioClientUtils minioClientUtils;private MinioConfig minioConfig;@ApiOperation(value = "上传文件,支持批量上传")@ApiImplicitParams({@ApiImplicitParam(name = "files", value = "文件流对象,接收数组格式", paramType = "query",required = true, dataType = "MultipartFile", allowMultiple = true)})@PostMapping("/uploadFile")public ApiResult uploadFile(@RequestParam(value = "files", required = true) MultipartFile[] files) {log.info(files.toString());     List<String> MinioResponseDTOList = new ArrayList<>();for (MultipartFile file : files) {String originalFilename = file.getOriginalFilename();//            获取文件拓展名String extName = FileUtil.extName(originalFilename);log.info("文件拓展名:" + extName);//            生成新的文件名,存入到miniolong millSeconds = Instant.now().toEpochMilli();String minioFileName = millSeconds + RandomStringUtils.randomNumeric(12) + "." + extName;String contentType = file.getContentType();log.info("文件mime:{}", contentType);//            返回文件大小,单位字节long size = file.getSize();log.info("文件大小:" + size);try {String bucketName = minioConfig.getBucketName();minioClientUtils.putObject(bucketName, file, minioFileName);String fileUrl = minioClientUtils.getObjectUrl(bucketName, minioFileName);             MinioResponseDTOList.add(fileUrl);} catch (Exception e) {log.error("上传文件出错:{}", e);return ApiResult.error("上传文件出错");}}return ApiResult.success(MinioResponseDTOList);}@GetMapping("/test")@ApiOperation(value = "测试minio文件上传")public ApiResult testPutObject() throws Exception {FileInputStream fileInputStream = new FileInputStream("C:\\Users\\MSI\\Desktop\\新建文本文档.txt");boolean bs = minioClientUtils.putObject("fsp-dev", "新建文本文档.txt", fileInputStream, "image/jpg");log.info("上传成功?" + bs);return ApiResult.success("上传成功");}}
  3. 测试接口
    在这里插入图片描述

4.1 背景

现在大家都是用的智能手机拍照,拍出来的照片小则 2-3 M,大则十几 M,所以导致图片显示较慢。思考再三,决定将图片进行压缩再上传图片服务器来解决图片显示慢的问题

4.2 开发准备

  1. 引入 maven 依赖

    <!-- 图片压缩 --><dependency>    <groupId>net.coobird</groupId>    <artifactId>thumbnailator</artifactId>    <version>0.4.8</version></dependency>

    本次我们选择了使用 thumbnailator 来作为压缩的工具

  2. thumbnailator 简介

    Thumbnailator 是一个用来生成图像缩略图的 Java 类库,通过很简单的代码即可生成图片缩略图,也可直接对一整个目录的图片生成缩略图
    支持图片缩放,区域裁剪,水印,旋转,保持比例

  3. 压缩准备
    判断是否是图片方法

    public boolean isPicture(String imgName) {    boolean flag = false;    if (StringUtils.isBlank(imgName)) {        return false;    }    String[] arr = {"bmp", "dib", "gif", "jfif", "jpe", "jpeg", "jpg", "png", "tif", "tiff", "ico"};    for (String item : arr) {        if (item.equals(imgName)) {            flag = true;            break;        }    }    return flag;}

4.3 压缩上传

public JSONObject uploadFile(MultipartFile file) throws Exception {    JSONObject res = new JSONObject();    res.put("code", 500);    // 判断上传文件是否为空    if (null == file || 0 == file.getSize()) {        res.put("msg", "上传文件不能为空");        return res;    }    // 判断存储桶是否存在    if (!client.bucketExists("test")) {        client.makeBucket("test");    }    // 拿到文件后缀名,例如:png    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);    // UUID 作为文件名    String uuid = String.valueOf(UUID.randomUUID());    // 新的文件名    String fileName = DateUtils.getYyyymmdd() + "/" + uuid + "." + suffix;        if (isPicture(suffix) && (1024 * 1024 * 0.1) <= file.getSize()) {        // 在项目根目录下的 upload 目录中生成临时文件        File newFile = new File(ClassUtils.getDefaultClassLoader().getResource("upload").getPath() + uuid + "." + suffix);        // 小于 1M 的        if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.3f).toFile(newFile);        }        // 1 - 2M 的        else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.2f).toFile(newFile);        }        // 2M 以上的        else if ((1024 * 1024 * 2) < file.getSize()) {            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.1f).toFile(newFile);        }        // 获取输入流        FileInputStream input = new FileInputStream(newFile);        // 转为 MultipartFile        MultipartFile multipartFile = new MockMultipartFile("file", newFile.getName(), "text/plain", input);        // 开始上传        client.putObject("test", fileName, multipartFile.getInputStream(), file.getContentType());        // 删除临时文件        newFile.delete();        // 返回状态以及图片路径        res.put("code", 200);        res.put("msg", "上传成功");        res.put("url", minioProp.getEndpoint() + "/" + "test" + "/" + fileName);    }    // 不需要压缩,直接上传    else {        // 开始上传        client.putObject("test", fileName, file.getInputStream(), file.getContentType());        // 返回状态以及图片路径        res.put("code", 200);        res.put("msg", "上传成功");        res.put("url", minioProp.getEndpoint() + "/" + "test" + "/" + fileName);    }    return res;}

遇到的问题:
Thumbnails.scale效果会导致图片大小变大
在这里插入图片描述

Thumbnails应该是存在bug,但是也一直没有更新版本,所以根据多次测试得来的结果:用jpg转成jpg效果最佳。所以当图片为png时,先改成jpg格式,再进行压缩。

public static String imgConvert(String tempDirPath, String fileName, String fileExt) throws IOException {    String srcPath = tempDirPath + fileName;  //原始图片路径    if("png".equals(fileExt)) {        //生成新图片名称    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");            String fileString = df.format(new Date()) + "_" + new Random().nextInt(1000) + ".jpg";                        //新图片全路径            String newJpg = tempDirPath + fileString;                     // 1、先转换成jpg              Thumbnails.of(srcPath).scale(1f).toFile(newJpg);                         //2.jpg图片压缩            Thumbnails.of(newJpg).scale(1f).outputQuality(0.25d).toFile(newJpg);                        //压缩成功后,删除png图片            File f = new File(srcPath);            f.delete();                        return fileString;    } else {    Thumbnails.of(srcPath).scale(1f).outputQuality(0.25d).toFile(srcPath);    }    return null;    }

来源地址:https://blog.csdn.net/qq_38055805/article/details/130216715

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯