上传图片的例子较多,以上传头像为例
首先在项目中需要上传头像的位置新建一个组件
下面代码基本都是固定格式
关键属性::http-request="upload" action="#"
使用自定义行为覆盖默认上传,注意一旦设置自定义上传行为之后,所有的上传操作都需要自己实现,比如数据处理,上传成功之后的后续操作,on-success钩子函数也不会继续触发
<template>
<div>
<el-upload
class="avatar-uploader"
action="#"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:http-request="upload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon" />
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: ''
}
},
methods: {
upload(file) {
console.log(file)
},
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw)
},
beforeAvatarUpload(file) {
const isPNG = file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isPNG) {
this.$message.error('上传头像图片只能是 PNG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isPNG && isLt2M
}
}
}
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
这里将上传头像的组件注册到全局
import UploadImg from '@/components/UploadImg'
const MyPlugin = {
install(Vue) {
// 省略其他....
+ Vue.component(UploadImg.name, UploadImg)
}
}
export default MyPlugin
安装插件npm i cos-js-sdk-v5 --save
在组件中实例化
以下写XXX的地方到组长或自己的账号下复制即可
// 下面的代码是固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
SecretId: 'xxx', // 身份识别ID
SecretKey: 'xxx' // 身份秘钥
})
upload(res) {
if (res.file) {
// 执行上传操作
cos.putObject({
Bucket: 'xxxxxx', /* 存储桶 */
Region: 'xxxx', /* 存储桶所在地域,必须字段 */
Key: res.file.name, /* 文件名 */
StorageClass: 'STANDARD', // 上传模式, 标准模式
Body: res.file // 上传文件对象
}, (err, data) => {
console.log(err || data)
// 上传成功之后
if (data.statusCode === 200) {
this.imageUrl = `https:${data.Location}`
}
})
}
}
上述步骤做完之后,腾讯云会生成一个对应的线上图片地址 ==> https:${data.Location}将其赋值给要修改的头像即可
致敬,码农!!!