原理:通过调用后台接口获取腾讯云秘钥,然后将秘钥以及文件信息上传到腾讯云,获取文件腾讯云存储信息,最后组件将腾讯云存储信息返回出去,在组件外部调用后台接口将腾讯云信息存到后台。
安装cos-js-sdk-v5依赖
npm i cos-js-sdk-v5 --save
uuid.js文件
在src的utils文件夹中新增uuid.js文件
/* eslint-disable */
export default (len, radix) => {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var uuid = [],
i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
system.config.js文件
在src的config文件夹中新增system.config.js文件
/**
* 系统配置文件
*/
/* eslint-disable */
// 系统配置 ,在模块中使用方法: this.$CONFIG.xxxx
const config = {
//系统名称
systemTitle:'安全生产标准化管理体系网',
//系统描述
systemDescription:'业界领先的信息聚合平台',
//系统底部 copyright@公司名称
footerComName:'信息科技有限公司',
//腾讯云存储
Bucket: 'test-1256342487',
Region: 'ap-chengdu',
//后台接口地址
serverUrl:'http://123.206.76.136/news/api'
}
export default config
在main.js文件中进行全局属性配置
import config from '@/config/system.config'
// 引入全局自定义配置文件
Vue.CONFIG = Vue.prototype.$CONFIG = config
封装组件
/* eslint-disable space-before-function-paren */
/* eslint-disable space-before-function-paren */
// eslint-disable-next-line vue/valid-template-root
<template>
<div class="clearfix">
<a-upload accept="image/*"
listType="picture-card"
:fileList="fileList"
@preview="handlePreview"
:remove="remove"
:beforeUpload="beforeUpload"
:customRequest="handleUpload">
<div v-if="fileList.length < maxNum">
<a-icon type="plus" />
<div class="ant-upload-text">Upload</div>
</div>
</a-upload>
<!-- 图片预览 -->
<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
<img alt="加载失败" style="width: 100%" :src="previewImage" />
</a-modal>
</div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
import { getCredential } from '@/api/upload'
import uuid from '@/utils/uuid'
/* eslint-disable */
export default {
name:"UploadImage",
props: {
files: {
type: Array,
required: false,
default: () => []
}
},
data() {
return {
fileList: [],
cos: null,
// 图片预览相关
previewVisible: false,
previewImage: '',
maxNum:1
}
},
watch:{
files(list){
this.fileList = list
}
},
created() {
// 初始化腾讯云上传
this.cos = new COS({
getAuthorization: (options, callback) => {
getCredential().then(res => {
if (res.success) {
const { result } = res
callback({
TmpSecretId: result.tmpSecretId,
TmpSecretKey: result.tmpSecretKey,
XCosSecurityToken: result.sessionToken,
ExpiredTime: result.expiredTime
})
} else {
this.$message.error(res.msg)
}
})
}
})
},
methods: {
// 限制上传数量
changeNum(maxNum){
this.maxNum = maxNum
},
// 图片预览关闭
handleCancel() {
this.previewVisible = false;
},
// 图片预览开启
handlePreview(file) {
this.previewImage = file.url || file.thumbUrl;
this.previewVisible = true;
},
// 上传之前判断文件类型
beforeUpload(file) {
// console.log("beforeUpload",file)
let isJPG = false
const picTypes = ["image/jpeg","image/png","image/bmp","image/tif"]
picTypes.forEach(item=>{
if(file.type.toLocaleLowerCase() == item){
isJPG = true
}
})
if(!isJPG){
this.$message.error("请上传图片类型:jpeg/png/bmp/tif")
return false
}
},
// 删除图片
remove(file){
// console.log("remove",file)
// console.log("remove",this.fileList)
let fileList = this.fileList.filter(item=>{
return item.uid != file.uid
})
this.fileList = fileList
this.$emit('change', fileList)
},
// 上传文件 返回腾讯云信息,通过事件将存储信息返回到父组件
handleUpload(info) {
const that = this
const { file } = info
// console.log("handleUpload",file)
const uid = uuid()
const extName = that.getExtName(file.name)
const fileName = file.name
that.cos.putObject(
{
Bucket: that.$CONFIG.Bucket,
Region: that.$CONFIG.Region,
Key: fileName,
Body: file, // 上传文件对象
onProgress: progressData => {
// that.progress = progressData.percent
// console.log(JSON.stringify(progressData))
}
},
(err, data) => {
if (err) {
that.$notification.error({
message: '文件上传错误',
description: err.Message
})
} else {
const url = `http://${data['Location']}`
that.fileList.push({
uid,
name: file.name,
status: 'done',
url
})
// console.log("handleUpload",that.fileList)
that.$emit('change', that.fileList)
that.$message.success('上传成功')
}
}
)
},
/**
* 获取后缀名
*/
getExtName(fileName) {
const index = fileName.lastIndexOf('.')
if (index > -1) {
return fileName.substring(index + 1)
} else {
return ''
}
}
}
}
</script>
<style lang="less" scoped>
.ant-upload-select-picture-card i {
font-size: 32px;
color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
margin-top: 8px;
color: #666;
}
</style>
使用
<upload-image ref="UploadImage"
:files="thumbnails"
@change="uploadThumbnail"></upload-image>
//获取腾讯云存储信息
uploadThumbnail(thumbnail){
console.log("uploadThumbnail",thumbnail)
},
//改变上传限制数量
changeNum(val){
this.$refs.UploadImage.changeNum(val)
},