上传图片到腾讯云回显示例
![](https://img.haomeiwen.com/i16566662/d08c5604c123d594.png)
子组件
1.前提:安装cos-js-sdk-v5和uuid插件
<template>
<el-upload
ref="upload"
class="upload-demo"
action="#"
:accept="accept"
:multiple="false"
:http-request="handlePreview"
:auto-upload="true"
:show-file-list="false"
>
<slot />
</el-upload>
</template>
import COS from 'cos-js-sdk-v5'
import { v4 as uuidv4 } from 'uuid';
export default {
props: {
accept: {
type: String,
default: ''
},
saveUrl: {
type: Object,
default: () => {}
},
filePathUrl: {
type: String,
default: ''
},
subData: {
type: Object,
default: () => {}
}
},
data () {
return {
cosClient: null,
secretId: 'AKIDkNm',
secretKey: 'NXTEn8',
BucketName: 'tx-sh-demo-1253490992',
Region: 'bp-shanghai'
}
},
computed: {},
watch: {},
async created () {
this.createCOS()
},
methods: {
createCOS () {
// 创建COS对象
this.cosClient = new COS({
SecretId: this.secretId,
SecretKey: this.secretKey
});
},
// 文件上传事件。覆盖默认上传
handlePreview (params) {
const { size, name } = params.file
if (!name) return
const suffix = name.split('.')[name.split('.').length - 1]
const uuid = uuidv4()
const saveName = this.filePathUrl + `/${uuid}.${suffix}`
// const saveName = `bigBook/softwareNum/${name}`
// 上传文件到腾讯云
this.cosClient.uploadFile({
Bucket: this.BucketName, // 填入您自己的存储桶,必须字段
Region: this.Region, // 存储桶所在地域,例如ap-beijing,必须字段
Key: saveName, // 存储在桶里的对象键(例如1.jpg,a/b/test.txt),必须字段
SliceSize: 1024 * 1024 * 5, // 触发分块上传的阈值,超过5MB使用分块上传,非必须
Body: params.file, // 必须,上传文件对象,可以是input[type="file"]标签选择本地文件后得到的file对象
onTaskReady: function (taskId) { /* 非必须 */
// console.log(taskId);
},
onProgress: function (progressData) { /* 非必须 */
// console.log(JSON.stringify(progressData));
},
onFileFinish: function (err, data, options) { /* 非必须 */
console.log(options.Key + '上传' + (err ? '失败' : '完成'));
}
}, (err, data) => {
const { statusCode, ETag, Location, RequestId } = data
if (statusCode == 200) {
// console.log(data);
// console.log('上传成功');
if (this.saveUrl?.url) {
const sub_param = {
fileSize: size,
fileName: name,
fileKey: 'https://' + Location,
md5: JSON.parse(ETag),
crc32: RequestId,
...this.subData
}
this.saveFileInfo(sub_param)
} else {
const file_obj = {
fileMsg: params.file,
cosMsg: data
}
this.$emit('uploadSuccess', file_obj);
}
} else {
console.log(err);
}
});
},
saveFileInfo (param) {
this.$ajax(this.saveUrl, param).then((res) => {
if (res.resultCode == 200) {
this.$message.success('上传成功');
this.$emit('uploadSuccess', true);
} else {
this.$message.warning('上传失败');
}
});
}
}
}
父组件使用
1.template中内容
<template>
<el-form-item label="商品图片" prop="fileId">
<div class="upload_box">
<abup-cos-upload
:accept="accept"
:sub-data="sub_data"
:save-url="saveUrl"
:file-path-url="filePathUrl"
@uploadSuccess="getImgMsg"
>
<span style="color:#409eff;margin-right:10px;">上传</span>
</abup-cos-upload>
<!-- 上传后回显图片 -->
<div class="">
<el-image :src="dataForm['downUrl']" fit="fill">
<div slot="error" class="image-slot">
<i class="el-icon-picture-outline"></i>
</div>
</el-image>
</div>
</div>
</el-form-item>
</template>
2.引入子组件
import AbupCosUpload from '@/components/FileCosUpload'
export default {
components: {
AbupCosUpload
},
data () {
return {
dataForm: {
fileId: '',
downUrl: ''
},
// 上传图片参数
accept: '.png,.jpg,.gif',
sub_data: {},
saveUrl: { url: '' },
filePathUrl: 'functionWarehouse/MerchantableGoods'
}
},
methods: {
getImgMsg (img) {
const { size, name, type } = img.fileMsg
const { Location, ETag, RequestId } = img.cosMsg
const param = {
id: '',
fileSize: size,
fileName: name,
fileKey: 'https://' + Location,
md5: JSON.parse(ETag),
hash: JSON.parse(ETag),
crc32: RequestId,
fileItem: '2',
fileType: type
}
this.$ajax(apiFileStoreInsert, param).then((res) => {
if (res.resultCode == 200) {
this.dataForm.fileId = res.data.fileId
this.dataForm.downUrl = res.data.downUrl
}
}).catch(() => {
})
}
}
}
网友评论