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)
}
)
},
注意!!!,如果删除的时候出现以下报错:
不要慌,这是因为权限问题,要去腾讯云里面加上删除权限就好了