栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

minio上传和下载文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

minio上传和下载文件

import brave.Tracer;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.xiaomi.commonbase.*;
import io.minio.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



@RestController
@RequestMapping("/common-manager")
public class MinioFileUploadController {

    private static Logger logger = LoggerFactory.getLogger(MinioFileUploadController.class);

    private RedisUtil redisUtil = SpringConfig.getBean(RedisUtil.class);

    public static SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.yyyy_MM_dd_HH_mm_ss);


    @Value("${minio.bucket_name}")
    private String bucketName;


    @Value("${minio.end_point}")
    private  String endPoint;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    Tracer tracer;


    

    @RequestMapping("/upload")
    public RspBean upload(@RequestParam(value="media") MultipartFile[] media) throws  Exception{

//        判断文件是否为空
        if (media==null || media.length==0){
            return new RspBean(RspCodeEnum.FAIL,"上传文件不能为空",tracer.currentSpan().context().traceIdString(),"fail");
        }

//        判断桶是否存在,不存在则创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }



        List objects = new ArrayList<>(media.length);

        for (MultipartFile file:media){
            String originalFilename = file.getOriginalFilename();
            // 新的文件名 = 存储桶名称_时间戳.后缀名
            String fileName = IdUtil.getId() + originalFilename.substring(originalFilename.lastIndexOf("."));

            objects.add(fileName);
            try{
                InputStream inputStream = file.getInputStream();

                minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                        inputStream, file.getSize(), -1
                ).contentType(file.getContentType()).build());

                inputStream.close();


                JSonObject resultJson = new JSonObject();
                resultJson.put("originalName",file.getOriginalFilename());
                resultJson.put("bucketName", bucketName);
                resultJson.put("fileName", fileName);
                resultJson.put("url",endPoint+"/"+bucketName+"/"+fileName);


                //将上传图片名称存入Redis,基于Redis的Set集合存储
                String format = sdf.format(new Date());
                Long aLong = Long.getLong(format);
                redisUtil.set("setmealPicResources",fileName,aLong);

                return new RspBean(RspCodeEnum.SUCCESS,"",tracer.currentSpan().context().traceIdString(),resultJson);

            }catch (Exception e){
                logger.info("上传接口异常:{}",e.getMessage());
                return new RspBean(RspCodeEnum.ERROR,"上传接口异常",tracer.currentSpan().context().traceIdString(),"fail");

            }
        }

        return new RspBean(RspCodeEnum.FAIL,"",tracer.currentSpan().context().traceIdString(),"fail");

    }

    
    @RequestMapping("/download")
    public RspBean download(@RequestParam(value="fileName")String fileName) throws  Exception{
        try {

            boolean flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());

            if (flag){
                //              获取对象信息
                StatObjectResponse response = minioClient.statObject(
                        StatObjectArgs.builder().bucket(bucketName).object(fileName).build()
                );
                if (response != null) {
                    minioClient.downloadObject(DownloadObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .filename(fileName)
                            .build());
                    return new RspBean(RspCodeEnum.SUCCESS, "下载接口成功", tracer.currentSpan().context().traceIdString(),
                            "success");

                }
            }else {
                return new RspBean(RspCodeEnum.ERROR,"桶不存在",tracer.currentSpan().context().traceIdString(),"fail");
            }

        }catch (Exception e){
            logger.info("下载接口异常:{}",e.getMessage());
            return new RspBean(RspCodeEnum.ERROR,"下载接口异常",tracer.currentSpan().context().traceIdString(),"fail");
        }
        return new RspBean(RspCodeEnum.ERROR,"下载接口异常",tracer.currentSpan().context().traceIdString(),"FAIL");


    }



}

 
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



@Configuration
public class MinioConfigs {

    @Value("${minio.end_point}")
    private String endPoint;
    @Value("${minio.access_key}")
    private String accessKey;
    @Value("${minio.secret_key}")
    private String secretKey;

    @Bean
    public MinioClient minioClient(){
        MinioClient build = MinioClient.builder().endpoint(endPoint).credentials(accessKey,secretKey).build();
        return build;
    }
}

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号