Spring Boot---(19)SpringBoot整合阿里云OSS存储服务2

初次使用请参考:Spring Boot---(18)SpringBoot整合阿里云OSS存储服务

本文介绍,如何获取某个bucket下某个目录中所有的文件名列表,如何删除某个文件。

1.工具类

package com.java4all.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.java4all.config.ConstantProperties;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by lightClouds917
 * Date 2018/2/7
 * Description:aliyunOSSUtil
 */
public class AliyunOSSUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 上传文件
     * @param file
     * @return
     */
    public static String upload(File file){
        logger.info("=========>OSS文件上传开始:"+file.getName());
        String endpoint=ConstantProperties.JAVA4ALL_END_POINT;
        String accessKeyId=ConstantProperties.JAVA4ALL_ACCESS_KEY_ID;
        String accessKeySecret=ConstantProperties.JAVA4ALL_ACCESS_KEY_SECRET;
        String bucketName=ConstantProperties.JAVA4ALL_BUCKET_NAME1;
        String fileHost=ConstantProperties.JAVA4ALL_FILE_HOST;

        String dateStr = format.format(new Date());

        if(null == file){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在,就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = fileHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                logger.info("==========>OSS文件上传成功,OSS地址:"+fileUrl);
                return fileUrl;
            }
        }catch (OSSException oe){
            logger.error(oe.getMessage());
        }catch (ClientException ce){
            logger.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }

    /**
     * 删除Object
     * @param fileKey
     * @return
     */
    public static String deleteBlog(String fileKey){
        logger.info("=========>OSS文件删除开始");
        String endpoint=ConstantProperties.JAVA4ALL_END_POINT;
        String accessKeyId=ConstantProperties.JAVA4ALL_ACCESS_KEY_ID;
        String accessKeySecret=ConstantProperties.JAVA4ALL_ACCESS_KEY_SECRET;
        String bucketName=ConstantProperties.JAVA4ALL_BUCKET_NAME1;
        String fileHost=ConstantProperties.JAVA4ALL_FILE_HOST;
        try {
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);

            if(!ossClient.doesBucketExist(bucketName)){
                logger.info("==============>您的Bucket不存在");
                return "您的Bucket不存在";
            }else {
                logger.info("==============>开始删除Object");
                ossClient.deleteObject(bucketName,fileKey);
                logger.info("==============>Object删除成功:"+fileKey);
                return "==============>Object删除成功:"+fileKey;
            }
        }catch (Exception ex){
            logger.info("删除Object失败",ex);
            return "删除Object失败";
        }
    }

    /**
     * 查询文件名列表
     * @param bucketName
     * @return
     */
    public static List getObjectList(String bucketName){
        List listRe = new ArrayList<>();
        String endpoint=ConstantProperties.JAVA4ALL_END_POINT;
        String accessKeyId=ConstantProperties.JAVA4ALL_ACCESS_KEY_ID;
        String accessKeySecret=ConstantProperties.JAVA4ALL_ACCESS_KEY_SECRET;
        try {
            logger.info("===========>查询文件名列表");
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            //列出blog目录下今天所有文件
            listObjectsRequest.setPrefix("blog/"+format.format(new Date())+"/");
            ObjectListing list = ossClient.listObjects(listObjectsRequest);
            for(OSSObjectSummary objectSummary : list.getObjectSummaries()){
                listRe.add(objectSummary.getKey());
            }
            return listRe;
        }catch (Exception ex){
            logger.info("==========>查询列表失败",ex);
            return new ArrayList<>();
        }
    }
}


2.获取列表

/**
     * 获取Object名称列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getObjectList",method = RequestMethod.GET)
    public List getObjectList(){
        String bucketName = ConstantProperties.JAVA4ALL_BUCKET_NAME1;
        List objectList = AliyunOSSUtil.getObjectList(bucketName);
        return objectList;
    }

调用接口,返回结果如下:

Spring Boot---(19)SpringBoot整合阿里云OSS存储服务2_第1张图片

我们看一下控制台的目录结构:

Spring Boot---(19)SpringBoot整合阿里云OSS存储服务2_第2张图片

请注意控制台的目录结构,注意java代码中prefix的写法。


3.删除文件

/**
     * 删除文件
     */
    @RequestMapping(value = "deleteBlog",method = RequestMethod.GET)
    @ResponseBody
    public String deleteBlog(){
        String ObjectKey = "blog/2018-02-08/10bce22715504455b47ff036b922ec2b-导入企业税收 - 55.xlsx";
        AliyunOSSUtil.deleteBlog(ObjectKey);
        return "删除成功";
    }

调用一下此接口,然后再次查询列表,结果如下:

Spring Boot---(19)SpringBoot整合阿里云OSS存储服务2_第3张图片

会发现,已经删除掉了。


你可能感兴趣的:((25)...Spring,Boot)