アリクラウドOSSストレージサービスツール類関連方法の作成


このツールクラスでは、ファイルupLoad(File file)、ファイル名からdownloadFile(String objectName、String localFileName)、フォルダの下にあるすべてのファイルlistFile()をダウンロードする3つの方法が主に用意されています.
/**
 * @Author: SnailClimb
 * @Date: 2018/12/1 16:56
 * @Description:    OSS       .
 * Java API    :https://help.aliyun.com/document_detail/32008.html?spm=a2c4g.11186623.6.703.238374b4PsMzWf
 */
@Component
public class AliyunOSSUtil {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
    private static String FILE_URL;
    private static String bucketName = AliyunOSSConfigConstant.BUCKE_NAME;
    private static String endpoint = AliyunOSSConfigConstant.END_POINT;
    private static String accessKeyId = AliyunOSSConfigConstant.AccessKey_ID;
    private static String accessKeySecret = AliyunOSSConfigConstant.AccessKey_Secret;
    private static String fileHost = AliyunOSSConfigConstant.FILE_HOST;


    /**
     *     。
     *
     * @param file          
     * @return             ,      "URL",          "   ,    。     :+    "
     */
    public static String upLoad(File file) {
        //     :true
        boolean isImage = true;
        //               ,      ,         URL  
        try {
            Image image = ImageIO.read(file);
            isImage = image == null ? false : true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        logger.info("------OSS      --------" + file.getName());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        //     
        if (file == null) {
            return null;
        }
        //   OSSClient  。
        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());
            if (isImage) {//     ,    URL :....
                FILE_URL = "https://" + bucketName + "." + endpoint + "/" + fileUrl;
            } else {
                FILE_URL = "   ,    。     :" + fileUrl;
            }

            //     
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //     (   )
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (result != null) {
                logger.info("------OSS      ------" + fileUrl);
            }
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return FILE_URL;
    }


    /**
     *          
     *
     * @param objectName           
     * @param localFileName          
     */
    public static void downloadFile(String objectName, String localFileName) {

        //   OSSClient  。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        //   OSS       。              ,      。
        ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFileName));
        //   OSSClient。
        ossClient.shutdown();
    }

    /**
     *    test         
     */
    public static void listFile() {
        //   OSSClient  。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        //   ListObjectsRequest  。
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);

        //   prefix     fun        。
        listObjectsRequest.setPrefix("test/");
        //     。
        ObjectListing listing = ossClient.listObjects(listObjectsRequest);
        //       。
        System.out.println("Objects:");
        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            System.out.println(objectSummary.getKey());
        }
        //     commonPrefix。
        System.out.println("CommonPrefixes:");
        for (String commonPrefix : listing.getCommonPrefixes()) {
            System.out.println(commonPrefix);
        }
        //   OSSClient。
        ossClient.shutdown();
    }
}

アリクラウドの期限切れobjectファイルを定期的に削除する
import java.util.Calendar;
import java.util.List;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.cnwan.controller.Helper.AliyunUtils;
 
/*
 *         object
 * */
@Component
public class DelObjectImpl {
    @Scheduled(cron = " 0 0 5 ? * MON ") //     5       
    public void myTest() {//   key   : key = "circle/uid/" + Calendar.getInstance().getTimeInMillis();
        List list = AliyunUtils.listFile("circle");
        for (String key : list) {
            String[] split = key.split("/");
            if (split[0].equals("circle")) {//  3       
                if (Calendar.getInstance().getTimeInMillis() > (Long.parseLong(split[2]) + 3600l * 1000 * 24 * 90)) {
                    AliyunUtils.deletePicture(key);
                    System.err.println("    : "+ key);
                }
            }
        }
    }
}