【JS实现腾讯云的cos图片上传和删除】

JS实现腾讯云的cos图片上传和删除

不多说,直接上代码!!!
具体请点击查看 腾讯云文档

首先我是多图片上传到腾讯云,以下是HTML代码

<el-upload
     ref="upload"
     :action="uploadApi"
     list-type="picture-card"
     :before-upload="handleBeforeUpload"
     multiple
     :file-list="fileList"
     :on-success="handleUploadSuccess"
   >
     <i slot="default" class="el-icon-plus"></i>
     <div slot="file" slot-scope="{ file }">
       <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
       <span class="el-upload-list__item-actions">
         <span class="el-upload-list__item-preview" @click="handlePreview(file)">
           <i class="el-icon-zoom-in"></i>
         </span>
         <!-- <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
           <i class="el-icon-download"></i>
         </span> -->
         <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file, fileList)">
           <i class="el-icon-delete"></i>
         </span>
       </span>
     </div>
   </el-upload>
   <el-dialog :visible.sync="dialogVisible" top="6vh" width="40%">
     <img width="100%" :src="dialogImageUrl" alt="" />
   </el-dialog>

上传的完整功能:

1.你可能回无法上传成功,遇到报跨域的问题,不要慌,去腾讯云里面添加一下域名的白名单就好了,比如我在本地,加的直接就是http://localhost:81
2:如果上传到测试环境又宝跨域,也要把测试的域名加到白名单

// 上传前的校验
     async handleBeforeUpload(file) {
       let that = this
       // 限制图片大小
       // const isLt500KB = file.size / 1024 < 500
       // if (!isLt500KB) {
       //   this.$message.error('上传图片大小不能超过 500KB!')
       //   return false
       // }
       // 获取 COS 临时密钥
       const res = await getCosCredentials()
       if (res.code !== 0) {
         this.$message.error('获取临时密钥失败!')
         return false
       }
       // 以下3个字段存下来是为了在删除的时候直接进行使用,避免再调一次上面的接口
       this.SecretId = res.data.credentials.tmpSecretId
       this.SecretKey = res.data.credentials.tmpSecretKey
       this.XCosSecurityToken = res.data.credentials.sessionToken
       // 初始化 COS 客户端
       let cos = new COS({
         SecretId: res.data.credentials.tmpSecretId,
         SecretKey: res.data.credentials.tmpSecretKey,
         XCosSecurityToken: res.data.credentials.sessionToken,
         Endpoint: 'xxxxxxxxxxx.com', // 填接口的域名就好
         Region: 'xxxxxxxx', /* 存储桶所在地域,例如ap-beijing,必须字段 */,
         Proxy: '',
         Bucket: 'xxxxxxx', /* 填入您自己的存储桶,必须字段 */,
       })
       this.cos = cos
       // 生成文件名
       const fileName = file.name
       // 拼接上传路径
       const uploadPath = fileName
       // 上传文件到 COS
       cos.sliceUploadFile(
         {
           Bucket: 'xxxxxx',
           Region: 'xxxxxxx',
           Key: uploadPath /* 存储在桶里的对象键(例如1.jpg,a/b/test.txt),必须字段 */,
           Body: file /* 必须,上传文件对象,可以是input[type="file"]标签选择本地文件后得到的file对象 */,
         },
         function (err, data) {
           console.log('err', err || data)
         }
       )
       return false
     },

删除的完整功能:

// 删除文件
    handleRemove(file) {
      let that = this
      let cos = new COS({
        SecretId: that.SecretId,
        SecretKey: that.SecretKey,
        XCosSecurityToken: that.XCosSecurityToken,
        Endpoint: 'xxxxxxxxxxx.com',
        Region: 'xxxxx',
        Proxy: '',
        Bucket: 'xxxxxxxxxxxxxx',
      })
      cos.deleteObject(
        {
          Bucket: 'xxxxxxxxxxx' /* 填入您自己的存储桶,必须字段 */,
          Region: 'xxxxxxxxxxxxxx' /* 存储桶所在地域,例如ap-beijing,必须字段 */,
          Key: file.name /* 存储在桶里的对象键(例如1.jpg,a/b/test.txt),必须字段 */,
        },
        function (err, data) {
          console.log(err || data)
        }
      )
    },

注意!!!,如果删除的时候出现以下报错:

在这里插入图片描述
不要慌,这是因为权限问题,要去腾讯云里面加上删除权限就好了

以下是效果图

在这里插入图片描述

结束!!!欢迎浏览

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用腾讯云官方提供的Java SDK,具体步骤如下: 1. 在pom.xml文件中引入腾讯云cos-java-sdk-v5依赖: ```xml <dependency> <groupId>com.qcloud</groupId> <artifactId>cos_api</artifactId> <version>5.6.19</version> </dependency> ``` 2. 创建腾讯云cos的配置类: ```java @Configuration public class TencentCosConfig { @Value("${tencent.cos.secretId}") private String secretId; @Value("${tencent.cos.secretKey}") private String secretKey; @Value("${tencent.cos.region}") private String region; @Value("${tencent.cos.bucketName}") private String bucketName; @Bean public COSCredentials cosCredentials() { return new BasicCOSCredentials(secretId, secretKey); } @Bean public ClientConfig clientConfig() { ClientConfig clientConfig = new ClientConfig(); clientConfig.setRegion(new Region(region)); return clientConfig; } @Bean public COSClient cosClient() { return new COSClient(cosCredentials(), clientConfig()); } @Bean public String bucketName() { return bucketName; } } ``` 其中,secretId和secretKey是腾讯云提供的访问密钥,region是存储桶所在的地域,bucketName是存储桶的名称。可以在配置文件中配置这些变量,这里用@Value注解获取。 3. 在上传文件的Controller中注入cosClient和bucketName,实现文件上传方法: ```java @RestController public class FileController { @Autowired private COSClient cosClient; @Autowired private String bucketName; @PostMapping("/uploadFile") public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception { ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(file.getSize()); objectMetadata.setContentType(file.getContentType()); String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(file.getOriginalFilename()); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getInputStream(), objectMetadata); cosClient.putObject(putObjectRequest); return "https://" + bucketName + ".cos." + "region" + ".myqcloud.com/" + fileName; } } ``` 这里上传文件的方式为MultipartFile类型,使用Apache Commons IO工具类获取文件后缀名,并用UUID生成随机文件名。然后创建PutObjectRequest对象,调用cosClient的putObject方法上传文件,最后将文件URL返回给前端。 希望以上信息能对你有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值