当前位置:网站首页>upload upload pictures to Tencent cloud, how to upload pictures
upload upload pictures to Tencent cloud, how to upload pictures
2022-08-05 04:20:00 【Hu Xiaochao】
Explain how to upload pictures to Tencent Cloud,Uploading to other third-party cloud disks is roughly the same;
一:First you need to have an account(Some can be skipped and watched directly)
1.Create a Tencent Cloud account,跟着提示操作即可(必须实名-为了安全),中间选择 对象存储cos,这里就创建好了;
2.Next you need to create the bucket,The permissions inside are :公有读,私有写;
3.设置cors规则,AllowHeader配置成* 号,This bucket is also created;
二:封装一个上传组件
这里使用到element组件库中的Upload来进行上传;
UploadUse can refer to the documentation-and combined with the code I gave;
项目中需要安装 cos-js-sdk-v5 --save Tencent cloud package can be uploaded;
The page is imported and an instance is created,Configure the bucket key-》Re-cloud products-》访问密钥
Below is a complete package,You can paste and copy directly;
<template>
<div>
<!--必填:
action:指定上传地址
file-list:A must-have array to manage pictures
样式:list-type Affects rendering style,指定 pictur-card 照片墙
钩子:on-preview The function is triggered when the image is clicked,A magnifying glass will appear on the binding,You need to display the popup yourself
on-remove A function that fires when an image is deleted
on-change Modify the function triggered by the picture-->
<el-upload
action="#"
list-type="picture-card"
:file-list="fileList"
:on-preview="onPreview"
:on-remove="onRemove"
:on-change="onChange"
:http-request="httpRequest"
:before-upload="beforeUpload"
:class="{hasImg:fileList.length>0}"
>
<i class="el-icon-plus" />
</el-upload>
<el-progress v-if="isShowPercent" :text-inside="true" :stroke-width="16" :percentage="percent" style="width:146px;" />
<el-dialog title="预览" :visible="isShowDialog" @close="isShowDialog=false">
<el-row type="flex" justify="center">
<img :src="previewImg" alt="">
</el-row>
</el-dialog>
</div>
</template>
<script>
// Introduce object storage tool library,创建实例
import COS from 'cos-js-sdk-v5'
// 前端使用固定密钥计算签名,该格式适用于前端调试
const cos = new COS({
SecretId: 'key number',
SecretKey: '密钥密码'
})
export default {
name: 'Dashboard',
data() {
return {
isShowPercent: false,
percent: 0,
isShowDialog: false,
previewImg: '',
// Each object in the file list is an image,url:显示图片路径,udi:唯一标识,status:状态
fileList: []
}
},
methods: {
// 点击文件列表中已上传的文件时的钩子,放大镜
onPreview(file) {
this.previewImg = file.url // 显示图片
this.isShowDialog = true // 弹窗
},
// Hook when removing files
onRemove(file, newFileList) {
this.fileList = newFileList
},
// 添加,上传成功/失败 都会触发
onChange(file, newFileList) {
// 由于 fileList The tie is one-way,需要手动替换
this.fileList = newFileList
},
// 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传.
beforeUpload(file) {
console.log('Triggered before upload')
console.log(file)
// 校验格式
const typeList = ['image/jpeg', 'image/png', 'image/gif']
if (!typeList.includes(file.type)) {
this.$message.error('目前只支持 jpg/png/gif 图片格式')
return false
}
// 校验大小
const maxSize = 5 * 1024 * 1024
if (file.size > maxSize) {
this.$message.error('图片大小不能超过 5M')
return false
}
},
// 覆盖默认的上传行为,The upload path can be customized
httpRequest(params) {
// Show a progress bar when uploading starts
this.isShowPercent = true
cos.putObject({
Bucket: 'chao-13', /* 填入您自己的存储桶,必须字段 */
Region: 'ap-nanjing', /* 存储桶所在地域,例如ap-beijing,必须字段 */
Key: params.file.name, /* 存储在桶里的对象键(例如1.jpg,a/b/test.txt),必须字段 */
StorageClass: 'STANDARD',
Body: params.file, // 上传文件对象
onProgress: (progressData) => {
console.log(JSON.stringify(progressData))
this.percent = progressData.percent * 100
}
}, (err, data) => {
console.log('The upload of the Tencent tool library is complete')
// Delay improves user experience-The progress bar disappears
setTimeout(() => {
this.isShowPercent = false
}, 1000)
console.log(err || data)
if (!err) {
// 手动处理 fileList
this.fileList[0].url = 'http://' + data.Location
this.fileList[0].status = 'success'
}
})
}
}
}
</script>
<style lang="scss" scoped>
.hasImg {
::v-deep .el-upload--picture-card {
display: none;
}
}
::v-deep img {
// Make the images in equal size,Keep the display intact
object-fit: cover;
}
</style>
In the above code, you need to pay attention to kill the default upload address-使用#号即可;
If you only need to upload a picture,Then set a dynamic style,Used to hide the upload component,It can be judged by storing the length of the image array;
The built-in functions of the components that need to be used to upload pictures are respectively:
onPreview(Triggered by clicking on an uploaded image):This is used to display pictures(放大);
beforeUpload(Triggered before upload) pictures in the function 格式、Check size etc;
onChange(Upload will trigger):Because data binding is single item,So you need to manually replace the picture;
onRemove(Remove image trigger):Used to delete unwanted pictures;
httpRequest(Default upload path):Configure the upload path of Tencent Cloud here,You need to fill in the corresponding data as needed;
Where to view the key?
三:The upload document could not be found?不知道httpRequest where to find the content?看这里就够了
第一步:点击spiThe document will have a pop-up box,点击SDKList entry
第二步:点击javaScript SDK快速入门
第三步:You can copy the upload object as needed
总结:The above is the whole process of how to upload,The code can be viewed in conjunction with the documentation-效果更好
边栏推荐
- In the hot summer, teach you to use Xiaomi smart home accessories + Raspberry Pi 4 to connect to Apple HomeKit
- how to measure distance from point to face in creo
- 国学*周易*梅花易数 代码实现效果展示 - 梅花心易
- Android interview question - how to write with his hands a non-blocking thread safe queue ConcurrentLinkedQueue?
- [8.1] Code Source - [The Second Largest Number Sum] [Stone Game III] [Balanced Binary Tree]
- iMedicalLIS listener (2)
- [Surveying] Quick Summary - Excerpt from Gaoshu Gang
- 机器学习概述
- [极客大挑战 2019]FinalSQL
- Event parse tree Drain3 usage and explanation
猜你喜欢
The log causes these pits in the thread block, you have to guard against
[8.1] Code Source - [The Second Largest Number Sum] [Stone Game III] [Balanced Binary Tree]
多御安全浏览器 V10.8.3.1 版正式发布,优化多项内容
JeeSite New Report
About the installation of sklearn library
Paparazzi: Surface Editing by way of Multi-View Image Processing
数字孪生技术在电力系统中的应用现状
Event parse tree Drain3 usage and explanation
App快速开发建设心得:小程序+自定义插件的重要性
There are a lot of 4T hard drives remaining, prompting "No space left on device" insufficient disk space
随机推荐
NPDP证书含金量高吗?跟PMP相比?
markdown如何换行——md文件
Mini Program_Dynamic setting of tabBar theme skin
4T硬盘剩余很多提示“No space left on device“磁盘空间不足
Cron(Crontab)--使用/教程/实例
Event parse tree Drain3 usage and explanation
Acid (ACID) Base (BASE) Principles for Database Design
[CISCN2019 South China Division]Web11
There are a lot of 4T hard drives remaining, prompting "No space left on device" insufficient disk space
日志导致线程Block的这些坑,你不得不防
为什么刚考完PMP,就开始准备软考了?
DEJA_VU3D - Cesium功能集 之 056-智图Arcgis地图纠偏
36-Jenkins-Job迁移
creo怎么测量点到面的距离
浅析主流跨端技术方案
[极客大挑战 2019]FinalSQL
【背包九讲——01背包问题】
UE4 通过重叠事件开启门
[CISCN2019 华东南赛区]Web11
四位数显表头设计