springboot实战之oss上传工具封装

2023-12-13 05:23:25

项目分析

实际项目中,使用到阿里云oss资源,项目用java开发,封装个工具,其他地方使用方便。

实现工具类

public class AliyunOssUploadUtils {
    protected static final Logger logger = LoggerFactory.getLogger(AliyunOssUploadUtils.class);

    private static volatile OSSClient ossClient = null;

    private static AliyunOssConfig aliyunOssConfig;
    @Autowired
    public AliyunOssUploadUtils(AliyunOssConfig aliyunOssConfig) {
        AliyunOssUploadUtils.aliyunOssConfig = aliyunOssConfig;
    }

    public static String uploadFile(MultipartFile file) throws Exception {
        //上传类型判断
        int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        // 编码文件名
        String filePathName = FileUploadUtils.extractFilename(file);
        // 文件路径名称
        filePathName = aliyunOssConfig.getFilehost() + "/" + filePathName;

        try {
            //判断是否是图片
            /**
            if("png".equals(ext)||"jpg".equals(ext)||"jpeg".equals(ext)||"webp".equals(ext)){
                logger.info("进行图片压缩处理",ext);
                String suffixName;
                String suffixNameOrigin = getExtensionName(file.getOriginalFilename());
                if ("png".equals(suffixNameOrigin)) {
                    suffixName = "png";
                } else {
                    suffixName = "jpg";
                }
                String originalPath = file.getOriginalFilename(); //获取原始文件名
                String contextPath = System.getProperty("user.dir"); //获取项目的路径
                String path = contextPath + File.separator + originalPath; //拼接文件路径
                File tempFile = new File(path); //通过路径创建文件对象
                file.transferTo(tempFile); //将MultipartFile对象转为File对象
                //压缩图片
                Thumbnails.of(tempFile)
                        .scale(0.5) //缩放比例
                        .outputFormat(suffixName) //输出格式
                        .toFile(tempFile);
                //上传Thumbnails.of(file.getInputStream()).scale(0.8f).outputFormat("jpg").outputQuality(0.5).toFile(uploadPath + random);
                ossClient.putObject(aliyunOssConfig.getBucketName(), filePathName, tempFile);
                tempFile.delete();
            }else {
                ossClient.putObject(aliyunOssConfig.getBucketName(), filePathName, file.getInputStream());
            }**/
            //Thumbnails.of(file.getInputStream()).scale(0.8f).outputFormat("jpg").outputQuality(0.5).toFile(filePathName);
            ossClient.putObject(aliyunOssConfig.getBucketName(), filePathName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return aliyunOssConfig.getUrl() + "/" + filePathName;
    }

    public static String addFileByByteArray(MultipartFile file, String fileName, byte[] byteArray) {
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        //公共读
        metadata.setObjectAcl(CannedAccessControlList.PublicRead);
        metadata.setCacheControl("no-cache");
        metadata.setHeader("Pragma", "no-cache");
        metadata.setContentDisposition("inline;filename=" + fileName);
        metadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
        try {
            // 编码文件名
            String filePathName = FileUploadUtils.extractFilename(file);
            // 文件路径名称
            fileName = aliyunOssConfig.getFilehost() + "/" + filePathName;
            //fileName = dir + "/" + fileName;
            ossClient.putObject(aliyunOssConfig.getBucketName(), fileName, new ByteArrayInputStream(byteArray), metadata);
        } catch (Exception e) {
            return null;
        } finally {
            ossClient.shutdown();
        }
        return aliyunOssConfig.getUrl() + "/" + fileName;//自己绑定OSS的域名

    }

    public static String getcontentType(String FilenameExtension) {
        if (".bmp".equalsIgnoreCase(FilenameExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(FilenameExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(FilenameExtension) ||
                ".jpg".equalsIgnoreCase(FilenameExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(FilenameExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(FilenameExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.visio";
        }
        if (".pptx".equalsIgnoreCase(FilenameExtension) ||
                ".ppt".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".docx".equalsIgnoreCase(FilenameExtension) ||
                ".doc".equalsIgnoreCase(FilenameExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(FilenameExtension)) {
            return "text/xml";
        }
        if (".png".equalsIgnoreCase(FilenameExtension)) {
            return "image/png";
        }
        return "image/jpg";
    }

    public static boolean deleteFile(String fileUrl) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        /** oss删除文件是根据文件完成路径删除的,但文件完整路径中不能包含Bucket名称。
         * 比如文件路径为:http://edu-czf.oss-cn-guangzhou.aliyuncs.com/2022/08/abc.jpg",
         * 则完整路径就是:2022/08/abc.jpg
         */
        int begin = ("https://" + aliyunOssConfig.getBucketName() + "." + aliyunOssConfig.getEndpoint() + "/").length(); //找到文件路径的开始下标
        String deleteUrl = fileUrl.substring(begin);

        try {
            // 删除文件请求
            ossClient.deleteObject(aliyunOssConfig.getBucketName() , deleteUrl);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


}

文章来源:https://blog.csdn.net/sccd2009/article/details/134681291
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。