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

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;
   
      // 创建阿里云登录凭证
     // public static CredentialsProvider credentialsProvider = new DefaultCredentialProvider(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    // 创建OSSClient实例。
     // public static OSS ossClient = new OSSClientBuilder().build(ENDPOINT, credentialsProvider);

       /**
        * 上传文件
        *
        * @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;
       } }
   
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
上传文件阿里云OSS可以通过以下步骤实现: 1. 引入aliyun-java-sdk-oss依赖 ``` <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-java-sdk-oss</artifactId> <version>3.10.0</version> </dependency> ``` 2. 创建OSSClient对象 ``` String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; String accessKeyId = "yourAccessKeyId"; String accessKeySecret = "yourAccessKeySecret"; String bucketName = "yourBucketName"; OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); ``` 3. 上传文件 ``` String objectName = "yourObjectName"; // 上传到OSS后的文件名,可以包含路径 File file = new File("yourLocalFile"); // 要上传的文件路径 ossClient.putObject(bucketName, objectName, file); ``` 4. 关闭OSSClient对象 ``` ossClient.shutdown(); ``` 完整的Java代码示例: ``` import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import java.io.File; public class OSSUploader { public static void main(String[] args) { String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; String accessKeyId = "yourAccessKeyId"; String accessKeySecret = "yourAccessKeySecret"; String bucketName = "yourBucketName"; String objectName = "yourObjectName"; // 上传到OSS后的文件名,可以包含路径 File file = new File("yourLocalFile"); // 要上传的文件路径 // 创建OSSClient对象 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 上传文件 ossClient.putObject(bucketName, objectName, file); // 关闭OSSClient对象 ossClient.shutdown(); } } ``` 需要注意的是,上传文件时可以指定上传后的文件名,也可以使用原文件名。同时,上传文件的大小不能超过OSS的限制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值