前言
在实际开发中,因为视频和图片占用的空间比较大,存放在自己的服务器上成本相对较高,我们可以选择将图片和视频资源存储到第三方云存储器(七牛云,阿里云,腾讯云等)上,我们自己的服务器上只存储地址.
腾讯云cos申请
1.使用现成的腾讯云服务创建一个免费的云存储(cloud.tencent.com/),创建账号并实名认证.
2.开通对象存储
3.创建存储桶
4.在存储桶列表中,选中存储桶设置cors规则(在左侧的菜单中选安全管理),因为我们是在测试上传,全部容许上传即可,真正的生产环境需要单独配置具体的域名和操作方法
5.配置云API秘钥
服务器属于个人的,需要一定的权限才能自由上传图片,这个负责权限验证的其实就是秘钥。拥有秘钥是进行上传的基础条件.
注:实际工作中,秘钥属于敏感信息,不能直接放到前端存储,容易产生安全问题,更好的做法是把秘钥交给后端管理,前端通过调用接口先获取秘钥,有了秘钥之后再进行上传操作.
图片上传组件
基于elementUI的upload组件实现图片上传.
1.在src/components/UploadImg文件夹下封装组件
<template>
<div>
<el-upload
class="avatar-uploader"
action="#" //用来指定文件要上传的地址,由于我们需要定制上传动作,这里设为#
:show-file-list="false" //是否显示上传的文件列表
: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)
},
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>
2.在src/components/index.js文件中全局注册
// 省略其他....
+ import UploadImg from '@/components/UploadImg'
// 1.定义插件(拓展Vue的功能)
const MyPlugin = {
install(Vue) {
// 省略其他....
+ Vue.component(UploadImg.name, UploadImg)
}
}
export default MyPlugin
3.安装依赖
npm i cos-js-sdk-v5 --save
4.在src/components/UploadImg文件下的全局组件中实例化cos对象
// 下面的代码是固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
SecretId: 'xxx', // 身份识别ID
SecretKey: 'xxx' // 身份秘钥
})
5.在src/components/UploadImg文件下的全局组件中使用cos对象完成上传(主要是用cos.putObjectapi来完成上传功能)
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}`
}
})
}
}
6.在src/components/UploadImg文件下的全局组件中补充上传进度条 (1)添加布局
<el-upload
class="avatar-uploader"
action="#"
:show-file-list="false"
: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-progress v-if="showProgress" :percentage="percentage" />
</el-upload>
(2)补充数据项
data () {
return {
// ...
percentage: 0, // 上传进度
isShow: false // 是否展示进度条
}
}
(3)更新数据项值
upload(res) {
if (res.file) {
// 显示进度条
增加 this.isShow = true
// 执行上传操作
cos.putObject({
Bucket: 'xxx', /* 存储桶 */
Region: 'ap-beijing', /* 存储桶所在地域,必须字段 */
Key: res.file.name, /* 文件名 */
StorageClass: 'STANDARD', // 上传模式, 标准模式
Body: res.file, // 上传文件对象
onProgress: (progressData) => {
console.log(JSON.stringify(progressData))
增加 this.percentage = progressData.percentage * 100
}
}, (err, data) => {
// 隐藏进度条
增加 this.isShow = false
console.log(err || data)
if (data.statusCode === 200) {
this.imageUrl = `https:${data.Location}`
}
})
}
}
7.在父组件中使用
<upload-img v-model="imageUrl" />
v-model是一个语法糖,等价于:value="imageUrl" @input="val=>imageUrl=val".
8.最终代码
<template>
<el-upload
class="avatar-uploader"
action="#"
:http-request="upload"
:show-file-list="false"
:before-upload="beforeAvatarUpload"
>
增加 <img v-if="value" :src="value" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon" />
<el-progress
v-if="isShow"
:percentage="percentage"
/>
</el-upload>
</template>
<script>
// 下面的代码是固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
SecretId: 'xxx', // 身份识别ID
SecretKey: 'xxx' // 身份秘钥
})
export default {
name: 'UploadImg',
增加 props: {
// 从父组件传递过来的v-model对应的值
value: { type: String, default: '' }
},
data() {
return {
// imageUrl: '',
percentage: 0, // 上传进度
isShow: false // 进度条是否可见
}
},
methods: {
upload(res) {
console.log('当前要上传的文件是', res.file)
if (res.file) {
// 执行上传操作
this.isShow = true // 进度条可见
cos.putObject({
Bucket: 'xxx', /* 存储桶 */
Region: 'ap-nanjing', /* 存储桶所在地域,必须字段 */
Key: res.file.name, /* 文件名 */
StorageClass: 'STANDARD', // 上传模式, 标准模式
Body: res.file, // 上传文件对象
onProgress: (progressData) => {
console.log('上传文件进度.....', JSON.stringify(progressData))
this.percentage = progressData.percentage * 100
}
}, (err, data) => {
this.isShow = false // 进度条不可见
console.log(err || data)
// 上传成功之后
if (data.statusCode === 200) {
const urlImg = `https://${data.Location}`
增加 this.$emit('input', urlImg)
}
})
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG && 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>
最后
希望整理的信息对您有所帮助,喜欢的话请帮忙点赞
如果有什么建议,欢迎在评论区留言
不足之处还请批评指教,谢谢!