欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 上传文件到阿里云oss、腾讯云cos、七牛云

程序员文章站 2024-02-19 11:10:46
...
  • 
    
    **1、第一步导入所需依赖包**
    <!--阿里oss-->
     	<dependency>
     		<groupId>com.aliyun.oss</groupId>
     		<artifactId>aliyun-sdk-oss</artifactId>
     	</dependency>
     	<!--七牛云-->
     	<dependency>
     		<groupId>com.qiniu</groupId>
     		<artifactId>qiniu-java-sdk</artifactId>
     	</dependency>
     	<!--腾讯cos-->
     	<dependency>
     		<groupId>com.qcloud</groupId>
     		<artifactId>cos_api</artifactId>
     	</dependency>
    
    **2、建模**
    
    @Data @TableName("sys_config_storage") @EqualsAndHashCode(callSuper =
    true) @ApiModel(description = "存储配置") public class SysConfigStorage
    extends Model<SysConfigStorage> implements Serializable {
        /**
         * PK
         */
        @ApiModelProperty(value = "PK")
        @TableId(type = IdType.AUTO)
        private Integer id;
    
        /**
         * 逻辑删除标记(0:显示;1:隐藏)
         */
        @ApiModelProperty(value = "逻辑删除标记")
        private String delFlag;
        /**
         * 创建时间
         */
        @ApiModelProperty(value = "创建时间")
        private Date createTime;
        /**
         * 最后更新时间
         */
        @ApiModelProperty(value = "最后更新时间")
        private Date updateTime;
        /**
         * 存储类型1、阿里OSS;2、七牛云;3、本地
         */
        @ApiModelProperty(value = "存储类型1、阿里OSS;2、七牛云;3、本地")
        private Integer storageType;
        /**
         * 地域节点
         */
        @ApiModelProperty(value = "地域节点")
        private String endpoint;
        /**
         * accessKeyId
         */
        @ApiModelProperty(value = "accessKeyId")
        private String accessKeyId;
        /**
         * **
         */
        @ApiModelProperty(value = "**")
        private String accessKeySecret;
        /**
         * 空间名称
         */
        @ApiModelProperty(value = "空间名称")
        private String bucket;
        /**
         * 图片水印内容
         */
        @ApiModelProperty(value = "图片水印内容")
        private String waterMarkContent;
    
        /**
         * 外链域名
         */
        @ApiModelProperty(value = "外链域名")
        private String outsideDomainName; }
    
    **3、编写上传接口**
    
        @ApiOperation(value = "上传文件")
        @PostMapping("/aliUpload")
        public R uploadFile(@RequestParam("file") MultipartFile mulFile,
                            @RequestParam("dir") String dir,
                            @RequestParam("fileType") String fileType) throws Exception {
            File file = FileUtils.multipartFileToFile(mulFile);
            dir = StrUtil.format("{}/{}", "12345", dir);
            SysConfigStorage sysConfigStorage = sysConfigStorageService
                    .getOne(Wrappers.<SysConfigStorage>query()
                            .lambda().eq(SysConfigStorage::getStorageType, "2"));
            if (sysConfigStorage == null) {
                throw new BaseServiceException("请先配置文件存储信息");
            }
            return R.ok(UploadFileUtils.uploadFile(file, dir, sysConfigStorage));
        }
    
    
    **4、上传类型选择** 
    
        public static String uploadFile(File file, String dir, SysConfigStorage sysConfigStorage) throws QiniuException {
            if (sysConfigStorage.getStorageType().equals(GeneralEnum.UPLOAD_TYPE_ALY.getCode()))
    {//阿里OSS
                AliOssUtils aliOssUtils = new AliOssUtils(sysConfigStorage);
                return aliOssUtils.uploadFile(file, dir);
            }
            if (sysConfigStorage.getStorageType().equals(GeneralEnum.UPLOAD_TYPE_QINIU.getCode()))
    {//七牛云
                QiNiuUtils qiNiuUtils = new QiNiuUtils(sysConfigStorage);
                return qiNiuUtils.uploadFile(file, dir);
            }
            // }else if("3".equals(sysConfigStorage.getStorageType())){//minio
            //     MinioUtils minioUtils = new MinioUtils(storageConfig);
            //     return minioUtils.uploadFile(file,dir);
            // }else if("4".equals(sysConfigStorage.getStorageType())){//腾讯cos
            //     QcloudCosUtils qcloudCosUtils = new QcloudCosUtils(storageConfig);
            //     return qcloudCosUtils.uploadFile(file,dir);
            // }
            // }
            return "";
        }
    
    
    **5、阿里云oss 工具**
        private final SysConfigStorage sysConfigStorage;
    
        /**
         * 上传文件
         *
         * @param file
         * @param dir  用户上传文件时指定的文件夹。
         */
        public String uploadFile(File file, String dir) {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(sysConfigStorage.getEndpoint(),
    sysConfigStorage.getAccessKeyId(),
    sysConfigStorage.getAccessKeySecret());
            String fileName = file.getName();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String key = dir + "/" + UUID.randomUUID() + "." + suffix;
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(sysConfigStorage.getBucket(), key, file);
            // 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);
            // 上传文件。
            ossClient.putObject(putObjectRequest);
            // 关闭OSSClient。
            ossClient.shutdown();
            // 解析结果
            String resultStr = "https://" + sysConfigStorage.getBucket() + "." + sysConfigStorage.getEndpoint() + "/" + key;
            return resultStr;
        }
    
    **6、七牛云上传工具**
        private final SysConfigStorage sysConfigStorage;
    
        /**
         * 上传文件
         *
         * @param file
         * @param dir  用户上传文件时指定的文件夹。
         */
        public String uploadFile(File file, String dir) throws QiniuException {
            //构造一个带指定 Region 对象的配置类
            Configuration cfg = new Configuration(Region.autoRegion());
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            //...生成上传凭证,然后准备上传
            String accessKey = sysConfigStorage.getAccessKeyId();
            String secretKey = sysConfigStorage.getAccessKeySecret();
            String bucket = sysConfigStorage.getBucket();
            //默认不指定key的情况下,以文件内容的hash值作为文件名
            String fileName = file.getName();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String key = preHandle(UUID.randomUUID() + "." + suffix, dir);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(file, key, upToken);
            String resultStr = getUrlPath(response);
            return resultStr;
        }
    
        private String preHandle(String fileName, String dir) {
            if (StrUtil.isNotBlank(dir) && !dir.startsWith("/")) {
                dir = "/" + dir;
            }
            String name = StrUtil.isBlank(fileName) ? RandomStringUtils.randomAlphanumeric(32) : fileName;
            if (StrUtil.isBlank(dir)) {
                return name;
            }
            String prefix = dir.replaceFirst("/", "");
            return (prefix.endsWith("/") ? prefix : prefix.concat("/")).concat(name);
        }
    
        private String getUrlPath(Response response) throws QiniuException {
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            String key = putRet.key;
            return sysConfigStorage.getOutsideDomainName() + (key.startsWith("/") ? key : "/" + key);
        }
    
    **7、腾讯cos**
    
        private final SysConfigStorage sysConfigStorage;
        public String uploadFile(File file,String dir) {
            // 1 初始化用户身份信息(secretId, secretKey)。
            String secretId = sysConfigStorage.getAccessKeyId();
            String secretKey = sysConfigStorage.getAccessKeySecret();
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
            // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
            Region region = new Region(sysConfigStorage.getEndpoint());
            ClientConfig clientConfig = new ClientConfig(region);
            // 3 生成 cos 客户端。
            COSClient cosClient = new COSClient(cred, clientConfig);
            // 指定要上传到的存储桶
            String bucketName = sysConfigStorage.getBucket();
            String fileName = file.getName();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String key = dir + UUID.randomUUID()+ "." + suffix;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            // 上传文件。
            cosClient.putObject(putObjectRequest);
            // 关闭OSSClient。
            cosClient.shutdown();
            Date expiration = new Date(new Date().getTime() + 5 * 60 * 10000);
            URL url = cosClient.generatePresignedUrl(bucketName, key, expiration);
            String resultStr = "https://" +  url.getHost() + "/" + key;
            return resultStr;
        }
    
    **8、其他工具类** public class FileUtils {
        public static File multipartFileToFile(MultipartFile mulFile) throws IOException {
            InputStream ins = mulFile.getInputStream();
            String fileName = mulFile.getOriginalFilename();
            String prefix = getFileNameNoEx(fileName)+ UUID.fastUUID();
            String suffix = "."+getExtensionName(fileName);
            File toFile = File.createTempFile(prefix,suffix);
            OutputStream os = new FileOutputStream(toFile);
            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();
            return toFile;
        }
    
        /**
         * 获取文件扩展名
         *
         */
        public static String getExtensionName(String filename) {
            if ((filename != null) && (filename.length() > 0)) {
                int dot = filename.lastIndexOf('.');
                if ((dot >-1) && (dot < (filename.length() - 1))) {
                    return filename.substring(dot + 1);
                }
            }
            return filename;
        }
    
        /**
         * 获取不带扩展名的文件名
         *
         */
        public static String getFileNameNoEx(String filename) {
            if ((filename != null) && (filename.length() > 0)) {
                int dot = filename.lastIndexOf('.');
                if ((dot >-1) && (dot < (filename.length()))) {
                    return filename.substring(0, dot);
                }
            }
            return filename;
        } }