minio上传文件图片

minio依赖

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

minio properties配置文件

#ip端口
minio.name=
#账号
minio.access=
#密码
minio.secret=
#桶名
minio.bucketName=picture

minio interface接口

...
import io.minio.MinioClient;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

@Service
@Component
public interface MinioService {
    /**
     * 初始化minio连接
     * @return
     */
    MinioClient initClient();

    /**
     * 获取MinIo中的桶列表
     * @return
     */
    Response<List<String>> getBucketsList();

    /**
     * 根据桶名字查文件列表
     * @param bucketName
     * @return
     */
    Response<List<String>> getFileListByBucketName(String bucketName);

    /**
     * 上传文件
     * @param file
     * @return
     */
    Response uploadFile(MultipartFile uploadFile);

    /**
     * 获取文件链接(对外)
     * @param fileName
     * @return
     */
    Response getFileUrl(String fileName);

    /**
     * 删除文件
     * @param bucketName
     * @param fileName
     * @return
     */
    Response removeFile(String bucketName, String fileName);
}

implement实现类

...
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

@Component
@PropertySource("classpath:/properties/image.properties")
public class MinioServiceImpl implements MinioService {

    public static final long serialVersionUID = 1L;

    public static Response response = new Response();

    @Value("${minio.name}")
    private String name;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.access}")
    private String access;
    @Value("${minio.secret}")
    private String secret;

    /**
     * 初始化minio连接
     *
     * @return
     */
    @Override
    public MinioClient initClient() {
        return MinioClient.builder().endpoint(name).credentials(access,secret).build();
    }

    /**
     * 获取MinIo中的桶列表
     *
     * @return
     */
    @Override
    public Response<List<String>> getBucketsList() {
        return null;
    }

    /**
     * 根据桶名字查文件列表
     *
     * @param bucketName
     * @return
     */
    @Override
    public Response<List<String>> getFileListByBucketName(String bucketName) {
        MinioClient minioClient = this.initClient();
        List<String> result = new ArrayList<>();
        // Check if the bucket already exists.
        try {
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) {
                response.setCode(500);
                response.setErr_msg("bucket不存在!");
                return response;
            }
            ListObjectsArgs arg = ListObjectsArgs.builder().bucket(bucketName).useUrlEncodingType(true).recursive(true).build();
            Iterable<Result<Item>> fileList = minioClient.listObjects(arg);
            Iterator<Result<Item>> iterator = fileList.iterator();
            while (iterator.hasNext()) {
                result.add(iterator.next().get().objectName());
            }
        } catch (Exception e) {
            response.setCode(500);
            response.setErr_msg(e.getMessage());
            return response;
        }
        response.setCode(0);
        response.setResponse(result);
        return response;

    }

    @Override
    public Response uploadFile(MultipartFile uploadFile){

        String url=null;
        try {
            File file = multipartFileToFile(uploadFile);

            // 校验图片类型是否正确 jpg|png|gif|bmp
            String fileName = uploadFile.getOriginalFilename();
            fileName = fileName.toLowerCase();
            int index = fileName.lastIndexOf(".");
            String fileType = fileName.substring(index);
            // 判断是否为图片类型
            if(!imageSet.contains(fileType)){
                // 用户上传的不是图片
                response.setCode(500);
                response.setErr_code("999999");
                response.setErr_msg("用户上传的不是图片");
                return response;
            }
            // 生成随机图片名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String realFileName = uuid + fileType;

            //String bucketName = "test1";
            MinioClient minioClient =this.initClient();

            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if(!isExist){
                response.setCode(500);
                response.setErr_code("999999");
                response.setErr_msg("bucket不存在!");
                return response;
            }
            FileInputStream in=new FileInputStream(file);
            PutObjectArgs arg= PutObjectArgs.builder().bucket(bucketName).object(realFileName).stream(in,file.length(),-1).build();
            minioClient.putObject(arg);
            url = minioClient.getPresignedObjectUrl(new GetPresignedObjectUrlArgs().builder().bucket(bucketName).object(realFileName).method(Method.GET).build());

            Map map = new HashMap();
            map.put("path", url);
            map.put("fileName",name+"/"+bucketName+"/"+realFileName);
            file.delete();
            response.setCode(0);
            response.setErr_code("000000");
            response.setErr_msg("");
            response.setResponse(map);
            return response;
        }catch (Exception e){
            response.setCode(500);
            response.setErr_code("999999");
            response.setErr_msg("上传图片异常!");
            return response;
        }

        // 上传的数据是否为恶意程序. 高度和宽度是否为null
        /*BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(uploadFile.getInputStream());
        } catch (IOException e) {
            response.setCode(500);
            response.setErr_msg("文件读取异常!");
            return response;
        }
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        if(width==0 || height ==0){
            response.setCode(500);
            response.setErr_msg("用户上图片不符合要求");
            return response;
         }*/
    }

    @Override
    public Response getFileUrl(String fileName) {
        // Create a minioClient with the MinIO Server name, Port, Access key and Secret key.
        MinioClient minioClient = initClient();
        // Check if the bucket already exists.
        InputStream result=null;
        try {
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if(!isExist){
                response.setCode(500);
                response.setErr_msg("bucket不存在!");
                return response;
            }
            result=minioClient.getObject(bucketName,fileName);
        } catch (Exception e) {
            response.setCode(500);
            response.setErr_msg(e.getMessage());
            return response;
        }
        String url=null;
        try {
            url=minioClient.getPresignedObjectUrl(new GetPresignedObjectUrlArgs().builder().bucket(bucketName).object(fileName).method(Method.GET).build());
        } catch (Exception e) {
            response.setCode(500);
            response.setErr_msg(e.getMessage());
            return response;
        }
        response.setCode(0);
        response.setResponse(url);
        return response;
    }

    @Override
    public Response removeFile(String bucketName, String fileName) {
        // Create a minioClient with the MinIO Server name, Port, Access key and Secret key.
        MinioClient minioClient = initClient();


        // Check if the bucket already exists.
        try {
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if(!isExist){
                response.setCode(500);
                response.setErr_msg("bucket不存在!");
                return response;
            }
            List<DeleteObject> objects = new ArrayList<>();
            objects.add(new DeleteObject(fileName));
            RemoveObjectsArgs arg= RemoveObjectsArgs.builder().bucket(bucketName).objects(objects).build();
            Iterable response=minioClient.removeObjects(arg);
            Iterator<Result<DeleteError>> it=response.iterator();
            while (it.hasNext()){
                it.next();
            }
        } catch (Exception e) {
            response.setCode(500);
            response.setErr_msg(e.getMessage());
            return response;
        }
        return response.ok();
    }

    // 定义图片长传格式
    private static Set<String> imageSet = new HashSet<>();
    static {
        imageSet.add(".jpg");
        imageSet.add(".png");
        imageSet.add(".gif");
        imageSet.add(".bmp");
    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }
    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

controller

/**
     * minio工作证件上传
     */
    @RequestMapping(value = "/minioUpload", method = RequestMethod.POST)
    @ApiOperation(value = "minio工作证件上传", notes = "minio工作证件上传")
    public Response minioUpload(@RequestParam(required = false) MultipartFile imageFile) {

        return minioService.uploadFile(imageFile);
    }

test

...
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MinioSdkTests  {
    @Autowired
    MinioService minioService;
   @Test
   public void testGetBucket() {
       // Create a minioClient with the MinIO Server name, Port, Access key and Secret key.
       MinioClient minioClient = new MinioClient("http://ip:8083", "name", "password");

       // Check if the bucket already exists.
       try {
           boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket("test1").build());
           System.out.println(isExist);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
    @Test
    public void testFilesInBucket() {
      System.out.println(minioService.getFileListByBucketName("test1"));
    }

    @Test
    public void testFileUrl() {
      System.out.println(minioService.getFileUrl("test1","test1.docx"));
    }

    @Test
    public void testPutFile() {
        // Create a minioClient with the MinIO Server name, Port, Access key and Secret key.
        MinioClient minioClient = MinioClient.builder().endpoint("http://ip:8083").credentials("name","password").build();
        File originalFile = new File("D:\\test\\test1.docx");

        System.out.println(minioService.uploadFile("test1",originalFile));
    }

    @Test
    public void testRemoveFile() {
       minioService.removeFile("test1","test1.docx");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值