千辛万苦整理出来的 阿里OSS工具类 #yyds干货盘点#

2021年11月24日 阅读数:4
这篇文章主要向大家介绍千辛万苦整理出来的 阿里OSS工具类 #yyds干货盘点#,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

参考博客:阿里OSS入门前端

bucket配置信息:alios.properties

在这里插入图片描述

OSS配置文件:AliOSSConfig.java

@Data
public class AliOSSConfig {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    private  AliOSSConfig(){
        Properties properties = new Properties();
        try {
            properties.load(AliOSSConfig.class.getResourceAsStream("/oss/alioss.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        endpoint = properties.getProperty("endpoint");
        accessKeyId= properties.getProperty("accessKeyId");
        accessKeySecret= properties.getProperty("accessKeySecret");
        bucketName= properties.getProperty("bucketName");
    }

    private static AliOSSConfig instance = new AliOSSConfig();

    public static AliOSSConfig getInstance() {
        return instance;
    }
}

工具类:AliOSSUtil.java

public class AliOSSUtil {
    private static final String endpoint = AliOSSConfig.getInstance().getEndpoint();
    private static final String accessKeyId = AliOSSConfig.getInstance().getAccessKeyId();
    private static final String accessKeySecret = AliOSSConfig.getInstance().getAccessKeySecret();
    private static final String bucketName = AliOSSConfig.getInstance().getBucketName();

    /**
     * 将文件上传到阿里OSS
     *
     * @param sourceFilePathName 本地文件
     * @param aimFilePathName    在阿里OSS中保存的能够包含路径的文件名
     * @return 返回上传后文件的访问路径
     * @throws FileNotFoundException
     */
    public static String upload(String sourceFilePathName, String aimFilePathName) throws FileNotFoundException {
        FileInputStream is = new FileInputStream(sourceFilePathName);

        if (aimFilePathName.startsWith("/")) {
            aimFilePathName = aimFilePathName.substring(1);
        }

        // 若是须要上传时设置存储类型与访问权限,请参考如下示例代码。
        ObjectMetadata metadata = new ObjectMetadata();
        int indexOfLastDot = aimFilePathName.lastIndexOf(".");
        String suffix = aimFilePathName.substring(indexOfLastDot);
        metadata.setContentType(getContentType(suffix));

        //避免文件覆盖
        aimFilePathName = aimFilePathName.substring(0, indexOfLastDot) + System.currentTimeMillis() + suffix;

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, aimFilePathName, is);
        //避免访问时将图片下载下来
        putObjectRequest.setMetadata(metadata);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.putObject(putObjectRequest);

        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
        URL url = ossClient.generatePresignedUrl(bucketName, aimFilePathName, expiration);

        // 关闭ossClient
        ossClient.shutdown();

        return url.toString();
    }

    /**
     * 网络实现上传头像到OSS
     *
     * @param multipartFile
     * @return
     */
    public static String upload(MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();
        // 获取文件名称
        String fileName = multipartFile.getOriginalFilename();

        // 避免文件覆盖
        int i = fileName.lastIndexOf(".");
        String suffix = fileName.substring(i);
        fileName = fileName.substring(0, i) + System.currentTimeMillis() + suffix;

        // 把文件按照日期进行分类
        // 获取当前日期
        String datePath = DateTimeFormatter.ISO_DATE.format(LocalDate.now());
        // 拼接fileName
        fileName = datePath + "/" + fileName;

        // 若是须要上传时设置存储类型与访问权限
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));

        // 上传文件到OSS时须要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
        putObjectRequest.setMetadata(metadata);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.putObject(putObjectRequest);

        //文件访问路径
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);

        // 关闭ossClient
        ossClient.shutdown();
        // 把上传到oss的路径返回
        return url.toString();
    }

    /**
     * 返回contentType
     *
     * @param FileNameExtension
     * @return
     */
    private static String getContentType(String FileNameExtension) {
        if (FileNameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FileNameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FileNameExtension.equalsIgnoreCase(".jpeg") ||
                FileNameExtension.equalsIgnoreCase(".jpg") ||
                FileNameExtension.equalsIgnoreCase(".png")
        ) {
            return "image/jpg";
        }
        return "image/jpg";
    }

    /**
     * 列举 指定路径下全部的文件的文件名
     * 若是要列出根路径下的全部文件,path= ""
     *
     * @param path
     * @return
     */
    public static List<String> listFileName(String path) {
        List<String> res = new ArrayList<>();
        // 构造ListObjectsRequest请求。
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);

        // 设置prefix参数来获取fun目录下的全部文件。
        listObjectsRequest.setPrefix(path);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 列出文件。
        ObjectListing listing = ossClient.listObjects(listObjectsRequest);
        // 遍历全部文件
        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            System.out.println(objectSummary.getKey());
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return res;
    }

    /**
     * 列举文件下全部的文件url信息
     */
    public static List<String> listFileUrl(String path) {
        List<String> res = new ArrayList<>();

        // 构造ListObjectsRequest请求
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);

        // 设置prefix参数来获取fun目录下的全部文件。
        listObjectsRequest.setPrefix(path);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 列出文件。
        ObjectListing listing = ossClient.listObjects(listObjectsRequest);
        // 遍历全部文件。

        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            //文件访问路径
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
            URL url = ossClient.generatePresignedUrl(bucketName, objectSummary.getKey(), expiration);
            res.add(url.toString());
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return res;
    }

    /**
     * 判断文件是否存在
     *
     * @param objectName
     * @return
     */
    public static boolean isFileExist(String objectName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        boolean res = ossClient.doesObjectExist(bucketName, objectName);
        return res;
    }

    /**
     * 经过文件名下载文件
     *
     * @param objectName    要下载的文件名
     * @param localFileName 本地要建立的文件名
     */
    public static void downloadFile(String objectName, String localFileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 下载OSS文件到本地文件。若是指定的本地文件存在会覆盖,不存在则新建。
        ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFileName));
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 删除文件或目录
     *
     * @param objectName
     */
    public static void delelteFile(String objectName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.deleteObject(bucketName, objectName);
        ossClient.shutdown();
    }

    /**
     * 批量删除文件或目录
     *
     * @param keys
     */
    public static void deleteFiles(List<String> keys) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 删除文件。
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
        java.util.List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();

        ossClient.shutdown();
    }
    /**
     * 建立文件夹
     *
     * @param folder
     * @return
     */
    public static String createFolder(String folder) {
        // 文件夹名
        final String keySuffixWithSlash = folder;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 判断文件夹是否存在,不存在则建立
        if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
            // 建立文件夹
            ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
            // 获得文件夹名
            OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
            String fileDir = object.getKey();
            ossClient.shutdown();
            return fileDir;
        }

        return keySuffixWithSlash;
    }

}

注意:为了不OSS连接出现 connection pool shutdown错误,不要在类中建立了OSSClient对象 ,由于这样作的话全部方法共用此实例对象,在前端很短的时间内连续提交,形成异常错误。应该将OSSClient对象在方法中建立。java

测试代码

class AliOSSUtilTest {

    @Test
    void upload() throws FileNotFoundException {
        //上传文件
        String url = AliOSSUtil.upload("E:\\图片\\510.jpg", "/aa/bb/ba.jpg");
        System.out.println(url);
    }

    @Test
    void listFileName() {
        List<String> res = AliOSSUtil.listFileName("aa/");
        res.forEach(System.out::println);
    }

    @Test
    void listFileUrl() {
        List<String> res = AliOSSUtil.listFileUrl("aa/");
        res.forEach(System.out::println);
    }

    @Test
    void isFileExist() {
        boolean res = AliOSSUtil.isFileExist("aa/bb/ab1637160001528.jpg");
        System.out.println(res);
    }

    @Test
    void downloadFile() {
        AliOSSUtil.downloadFile("aa/bb/ab1637160001528.jpg", "d:/aaawer.jpg");
    }

    @Test
    void delelteFile() {
        AliOSSUtil.delelteFile("aa/bb/ab1637160001528.jpg");
    }

    @Test
    void deleteFiles() {
        List<String> keys = List.of("aa/bb/ab1637160001528.jpg", "aa/bb/ba1637160268079.jpg","aa/bb/cc");
        AliOSSUtil.deleteFiles(keys);
    }

    @Test
    void createFolder() {
        String folder = AliOSSUtil.createFolder("aa/bb/cc");
        System.out.println(folder);
    }

}