ICE.ICE|

韩憨

园龄:4年7个月粉丝:42关注:47

minio实现文件上传下载和删除功能

https://blog.csdn.net/tc979907461/article/details/106673570?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare

minio的中文文档:https://docs.min.io/cn/

minio安装

  1. 首先查询docker镜像:
    docker search minio
    在这里插入图片描述

  2. 选着stars最高的那个拉取:
    docker pull minio/minio
    在这里插入图片描述

  3. 启动minio服务器,并设置端口号,容器名,账号和密码:
    docker run -p 9000:9000 --name minio -e MINIO_ACCESS_KEY=tanchuntcc -e MINIO_SECRET_KEY=tanchuntcc -v /data:/data minio/minio server /data
    在这里插入图片描述

minio操作

  1. 启动成功后,访问你minio的ip地址,这里我docker安装在本机,所以是http://localhost:9000,输入刚刚设置的账号密码。
    在这里插入图片描述

  2. 登陆后右下角可以创建bucket.
    在这里插入图片描述在这里插入图片描述

  3. 创建多个bucket后
    在这里插入图片描述

  4. 可以选择编辑和删除
    在这里插入图片描述

  5. 可以点击右下角上传文件
    在这里插入图片描述

  6. 支持各种类型的文件:
    在这里插入图片描述

首先创建一个Springboot项目,在resources中的application.yml文件添加如下配置:

server:
  port: 8080
  
spring:
  servlet:
    multipart:
      enabled: true #开启文件上传
      max-file-size: 500MB
      max-request-size: 500MB

minio:
  endpoint: http://localhost:9000 #Minio服务所在地址
  bucketName: tcc #存储桶名称
  accessKey: tanchuntcc #访问的key
  secretKey: tanchuntcc #访问的秘钥

 

添加minio的maven依赖:

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

 

controller的代码如下:

@RestController("/minioDemo")
public class MinioDemoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MinioDemoController.class);

    @Value("${minio.endpoint}")
    private  String ENDPOINT;
    @Value("${minio.bucketName}")
    private  String BUCKETNAME;
    @Value("${minio.accessKey}")
    private  String ACCESSKEY;
    @Value("${minio.secretKey}")
    private  String SECRETKEY;

    //文件创建
    @PostMapping
    public String upload(MultipartFile file) {
        String s=null;
        try {
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
            //存入bucket不存在则创建,并设置为只读
            if (!minioClient.bucketExists(BUCKETNAME)) {
                minioClient.makeBucket(BUCKETNAME);
                minioClient.setBucketPolicy(BUCKETNAME, "*.*", PolicyType.READ_ONLY);
            }
            String filename = file.getOriginalFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 文件存储的目录结构
            String objectName = sdf.format(new Date()) + "/" + filename;
            // 存储文件
            minioClient.putObject(BUCKETNAME, objectName, file.getInputStream(), file.getContentType());
            LOGGER.info("文件上传成功!");
            s=ENDPOINT + "/" + BUCKETNAME + "/" + objectName;
        } catch (Exception e) {
            LOGGER.info("上传发生错误: {}!", e.getMessage());
        }
        return s;
    }

    //文件删除
    @DeleteMapping
    public String delete(String name) {
        try {
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
            minioClient.removeObject(BUCKETNAME, name);
        } catch (Exception e) {
            return "删除失败"+e.getMessage();
        }
        return "删除成功";
    }
}

    @GetMapping
    public void downloadFiles(@RequestParam("filename") String filename, HttpServletResponse httpResponse) {

        try {

            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
            InputStream object = minioClient.getObject(BUCKETNAME, filename);
            byte buf[] = new byte[1024];
            int length = 0;
            httpResponse.reset();

            httpResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            httpResponse.setContentType("application/octet-stream");
            httpResponse.setCharacterEncoding("utf-8");
            OutputStream outputStream = httpResponse.getOutputStream();
            while ((length = object.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            outputStream.close();
        } catch (Exception ex) {
            LOGGER.info("导出失败:", ex.getMessage());
        }
    }

 

 

编写好demo程序后使用postman进行测试:使用postman文件上传时选择body中的form-data选项,然后属性栏里面选择file属性就可以实现文件上传了。
在这里插入图片描述

删除文件时输入文件的相对路径即可删除:
在这里插入图片描述
导出文件时填好文件名称,选择save and download即可在postman中导出文件:
在这里插入图片描述

 

示例

==============================================================================

<!-- minio工具类-->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>3.0.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.22</version>
<scope>compile</scope>
</dependency>

==============================================================================

InputStream inputStream = new FileInputStream(files.get(i));
MultipartFile multipartFile = new MockMultipartFile(files.get(i).getName(), files.get(i).getName(), ContentType.IMAGE_BMP.toString(), inputStream);
String path = MinioUtil.upload(multipartFile, infoResult.getString("specimenId"), i);
inputStream.close();

 

===============================================================================

package com.kanghua.manager.common.util;

import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
public class MinioUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(MinioUtil.class);

private static String ENDPOINT;
private static String BUCKETNAME;
private static String ACCESSKEY;
private static String SECRETKEY;

@Value("${minio.endpoint}")
public void setENDPOINT(String ENDPOINT) {
MinioUtil.ENDPOINT = ENDPOINT;
}

@Value("${minio.bucketName}")
public void setBUCKETNAME(String BUCKETNAME) {
MinioUtil.BUCKETNAME = BUCKETNAME;
}

@Value("${minio.accessKey}")
public void setACCESSKEY(String ACCESSKEY) {
MinioUtil.ACCESSKEY = ACCESSKEY;
}

@Value("${minio.secretKey}")
public void setSECRETKEY(String SECRETKEY) {
MinioUtil.SECRETKEY = SECRETKEY;
}

public static MinioClient minioClient;

/**
* 初始化minio配置
*/
@PostConstruct
public void init() {
try {
log.info("Minio Initialize........................");
minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
//createBucket(BUCKETNAME);
log.info("Minio Initialize........................successful");
} catch (Exception e) {
e.printStackTrace();
log.error("初始化minio配置异常: 【{}】", e.fillInStackTrace());
}
}

/**
* 文件创建
*/
@PostMapping
public static String upload(MultipartFile file, String specimenId, int i) {
String s = null;
try {
//MinioClient minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
//存入bucket不存在则创建,并设置为只读
if (!minioClient.bucketExists(BUCKETNAME)) {
minioClient.makeBucket(BUCKETNAME);
minioClient.setBucketPolicy(BUCKETNAME, "*.*", PolicyType.READ_ONLY);
}
String filename = specimenId + "_" + (i + 1 + "") + file.getName().substring(file.getName().lastIndexOf("."));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 文件存储的目录结构
String objectName = sdf.format(new Date()) + "/" + filename;
// 存储文件
minioClient.putObject(BUCKETNAME, objectName, file.getInputStream(), file.getContentType());
LOGGER.info("文件上传成功!");
s = ENDPOINT + "/" + BUCKETNAME + "/" + objectName;
LOGGER.info("文件上传地址:" + ENDPOINT + "/" + BUCKETNAME + "/" + objectName);
} catch (Exception e) {
LOGGER.info("上传发生错误: {}!", e.getMessage());
}
return s;
}

//文件删除
@DeleteMapping
public String delete(String name) {
try {
MinioClient minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
minioClient.removeObject(BUCKETNAME, name);
} catch (Exception e) {
return "删除失败" + e.getMessage();
}
return "删除成功";
}


@GetMapping
public void downloadFiles(@RequestParam("filename") String filename, HttpServletResponse httpResponse) {

try {

MinioClient minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
InputStream object = minioClient.getObject(BUCKETNAME, filename);
byte buf[] = new byte[1024];
int length = 0;
httpResponse.reset();

httpResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
httpResponse.setContentType("application/octet-stream");
httpResponse.setCharacterEncoding("utf-8");
OutputStream outputStream = httpResponse.getOutputStream();
while ((length = object.read(buf)) > 0) {
outputStream.write(buf, 0, length);
}
outputStream.close();
} catch (Exception ex) {
LOGGER.info("导出失败:", ex.getMessage());
}

}

}

本文作者:韩憨

本文链接:https://www.cnblogs.com/hanby/p/14297199.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   韩憨  阅读(10377)  评论(0编辑  收藏  举报
//看板娘

哥伦布

评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 隔离 (Studio Live Duet) 陈凯咏,林家谦
  2. 2 明知做戏 吴雨霏
  3. 3 残酷游戏 卫兰
  4. 4 你,好不好? 周兴哲
  5. 5 我可以 蔡旻佑
  6. 6 云烟成雨 房东的猫
  7. 7 说散就散 JC 陈咏桐
  8. 8 我配不上你 夏天Alex
  9. 9 不再联系 夏天Alex
  10. 10 等我先说 夏天Alex
  11. 11 我知道他爱你 夏天Alex
  12. 12 多想在平庸的生活拥抱你 隔壁老樊
  13. 13 这一生关于你的风景 隔壁老樊
  14. 14 我曾 隔壁老樊
  15. 15 关于孤独我想说的话 隔壁老樊
  16. 16 过客 周思涵
  17. 17 备爱 周思涵
  18. 18 嚣张 en
  19. 19 海口 后弦
我可以 - 蔡旻佑
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

寄 没有地址的信

这样的情绪 有种距离

你 放着谁的歌曲

你 放着谁的歌曲

是怎样的心情

能不能说给我听

雨 下得好安静

是不是你偷偷在哭泣

幸福 真的不容易

在你的背景 有我爱你~

我可以 陪你去看星星

不用再多说明

我就要和你在一起

我不想 又再一次和你分离

我多么想每一次的美丽

是因为你

寄 没有地址的信

寄 没有地址的信

这样的情绪 有种距离

你 放着谁的歌曲

是怎样的心情

能不能说给我听

雨 下得好安静

是不是你偷偷在哭泣

幸福 它真的不容易

在你的背景 有我爱你~

我可以 陪你去看星星

不用再多说明

我就要和你在一起

我不想 又再一次和你分离

我多么想每一次的美丽

是因为你

我可以 陪你去看星星

我可以 陪你去看星星

不用再多说明

我就要和你在一起

我不想 又再一次和你分离

我多么想每一次的美丽

是因为你

He...

He...

点击右上角即可分享
微信分享提示