Minio的安装&springBoot整合Minio进行上传下载代码案例

Minio简介

Minio是Apache License v2.0下发布的对象存储服务器。它与Amazon S3云存储服务兼容。它最适合存储非结构化数据,如照片,视频,日志文件,备份和容器/ VM映像。对象的大小可以从几KB到最大5TB
Minio服务器足够轻,可以与应用程序堆栈捆绑在一起,类似于NodeJS,Redis和MySQL。

Minio Docker安装

1. docker search minio --查找镜像
2. docker pull minio/minio --安装镜像
3. docker run -p 9018:9000 --name minio1 
  -e "MINIO_ACCESS_KEY=AKIAIOSFODNN7EXAMPLE" 
  -e "MINIO_SECRET_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" 
  -v /mnt/data:/data 
  -v /mnt/config:/root/.minio 
  minio/minio server /data
4.docker logs 容器Id --查看minio账号密码
image-20200804152628168.png

**注:Minio的安装具体步骤可以看这篇:https://www.jianshu.com/p/68ac0477291d (推荐)
或者是 https://blog.csdn.net/L531003231/article/details/102969890?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param
**

Minio 整合SpringBoot 案例

ps:下面代码出现的salt 是我自己创建的bucket

  1. Minio相关依赖
        
            com.alibaba
            fastjson
            1.2.7
        
 
        
            io.minio
            minio
            6.0.11
        
     
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
  1. 配置文件增加Minio相关配置
minio:
  endpoint: 自己的minio地址
  accesskey: 账号
  secretkey: 密码

3.Minio实体类

@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioProp {
    /**
    连接地址
     */
    private String endpoint;
    /**
     * 用户名
     */
    private String accesskey;
    /**
     * 密码
     */
    private String secretkey;
}
  1. Minio配置类
@Configuration
@EnableConfigurationProperties(MinioProp.class)
public class MinioConfig {

    @Autowired
    private MinioProp minioProp;

    /**
     * 获取MinioClient
     */
    @Bean
    public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
        return new MinioClient(minioProp.getEndpoint(),minioProp.getAccesskey(),minioProp.getSecretkey());
    }

}

5.Minio工具类(查询bucket/上传文件/获取文件/删除文件...)

@Component
public class MinioUtils {

    @Autowired
    private MinioProp minioProp;

    @Autowired
    private MinioClient client;

    /**
     * 创建bucket
     */
    public void createBucket(String bucketName) throws Exception{
        if (!client.bucketExists(bucketName)) {
            client.makeBucket(bucketName);
        }
    }

    /**
     * 上传文件
     */
    public JSONObject uploadFile(MultipartFile file,String bucketName) throws Exception{
        JSONObject res = new JSONObject();
        res.put("code",0);
        //判断文件是否为空
        if (null == file || 0 == file.getSize()) {
            res.put("msg","上传文件不能为空");
            return res;
        }
        //判断存储桶是否存在  不存在则创建
        createBucket(bucketName);
        //文件名
        String originalFilename = file.getOriginalFilename();
        //新的文件名 = 存储桶文件名_时间戳.后缀名
        String filelName = bucketName + "_" +
                System.currentTimeMillis() +
                originalFilename.substring(originalFilename.lastIndexOf("."));
        //开始上传
        client.putObject(bucketName,filelName,file.getInputStream(),file.getContentType());
        res.put("code",1);
        res.put("msg",minioProp.getEndpoint() + "/" + bucketName + "/" + filelName);
        return res;
    }

    /**
     * 获取全部bucket
     */
    public List getAllBuckets() throws Exception{
        return client.listBuckets();
    }

    /**
     * 根据bucketName获取信息
     *
     * @param bucketName bucket名称
     */
    public Optional getBucket(String bucketName) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
        return client.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
    }

    /**
     * 根据bucketName删除信息
     *
     * @param bucketName bucket名称
     */
    public void removeBucket(String bucketName) throws Exception{
        client.removeBucket(bucketName);
    }
    /**
     * 获取⽂件外链
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @param expires 过期时间 <=7
     * @return url
     */
    public String getObjectURL(String bucketName, String objectName, Integer expires) throws Exception{
        return client.presignedGetObject(bucketName, objectName, expires);
    }
    /**
     * 获取⽂件
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @return ⼆进制流
     */
    public InputStream getObject(String bucketName, String objectName) throws Exception{
        return client.getObject(bucketName, objectName);
    }
    /**
     * 上传⽂件
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @param stream ⽂件流
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#putObject
     */
    public void putObject(String bucketName, String objectName, InputStream stream) throws
            Exception {
        client.putObject(bucketName, objectName, stream, stream.available(),
                "application/octet-stream");
    }
    /**
     * 上传⽂件
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @param stream ⽂件流
     * @param size ⼤⼩
     * @param contextType 类型
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#putObject
     */
    public void putObject(String bucketName, String objectName, InputStream stream, long
            size, String contextType) throws Exception {
        client.putObject(bucketName, objectName, stream, size, contextType);
    }
    /**
     * 获取⽂件信息
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#statObject
     */
    public ObjectStat getObjectInfo(String bucketName, String objectName) throws Exception
    {
        return client.statObject(bucketName, objectName);
    }
    /**
     * 删除⽂件
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @throws Exception https://docs.minio.io/cn/java-client-apireference.html#removeObject
     */
    public void removeObject(String bucketName, String objectName) throws Exception {
        client.removeObject(bucketName, objectName);
    }
}

6.Controller类

@Controller
public class MinioController {

    @Autowired
    private MinioUtils minioUtils;

    /**
     * 初始化页面
     */
    @GetMapping("init")
    public String init(){
        return "file";
    }

    /**
     * 上传文件
     */

    @PostMapping("/upload")
    public void upload(@RequestParam(name = "file",required = false)MultipartFile file){
        JSONObject res = null;
        try {
            res = minioUtils.uploadFile(file,"salt");
        }catch (Exception e){
            e.printStackTrace();
            res.put("code",0);
            res.put("msg","上传失败" + e.getMessage());
        }
        System.out.println(res.toString());
    }

    /**
     * 删除文件
     * @param objectName
     * @throws Exception
     */
    @RequestMapping("/delete/{objectName}")
    public void delete(@PathVariable("objectName") String objectName) throws Exception{
        minioUtils.removeObject("salt",objectName);
        System.out.println("删除成功");
    }

    /**
     * 下载文件到本地
     * @param objectName
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/download/{objectName}")
    public ResponseEntity download2(@PathVariable("objectName") String objectName, HttpServletResponse response) throws Exception{
        ResponseEntity responseEntity = null;
        InputStream stream = null;
        ByteArrayOutputStream output = null;
        try {
            // 获取"myobject"的输入流。
            stream = minioUtils.getObject("salt", objectName);
            if (stream == null) {
                System.out.println("文件不存在");
            }
            //用于转换byte
            output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = stream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            byte[] bytes = output.toByteArray();

            //设置header
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Accept-Ranges", "bytes");
            httpHeaders.add("Content-Length", bytes.length + "");
//            objectName = new String(objectName.getBytes("UTF-8"), "ISO8859-1");
            //把文件名按UTF-8取出并按ISO8859-1编码,保证弹出窗口中的文件名中文不乱码,中文不要太多,最多支持17个中文,因为header有150个字节限制。
            httpHeaders.add("Content-disposition", "attachment; filename=" + objectName);
            httpHeaders.add("Content-Type", "text/plain;charset=utf-8");
//            httpHeaders.add("Content-Type", "image/jpeg");
            responseEntity = new ResponseEntity(bytes, httpHeaders, HttpStatus.CREATED);

        } catch (MinioException e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                stream.close();
            }
            if (output != null) {
                output.close();
            }
        }
        return responseEntity;
    }

    /**
     * 在浏览器预览图片
     * @param objectName
     * @param response
     * @throws Exception
     */
    @RequestMapping("/preViewPicture/{objectName}")
    public void download1(@PathVariable("objectName") String objectName, HttpServletResponse response) throws Exception{
        response.setContentType("image/jpeg");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            InputStream stream = minioUtils.getObject("salt",objectName);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = stream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            byte[] bytes = output.toByteArray();
            out.write(bytes == null ? new byte[0]:bytes);
            out.flush();
        }finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

  1. 简单页面



    
    测试minio上传


文件:

前面工具类可以参考:https://www.bilibili.com/read/cv6014961
经过测试,上传,删除,下载都已实现

你可能感兴趣的:(Minio的安装&springBoot整合Minio进行上传下载代码案例)