图片存储方案
存到三方云服务器(阿里云,七牛云,腾讯云)
各种云有专门的为图片存储提供的云服务器,我们自己的服务器只存储图片地址即可
腾讯云cos申请配置
创建账号并实名认证
开通对象存储
创建存储桶
设置cors规则
在存储桶列表中,选中存储桶
在左侧的菜单中选安全管理
配置云API秘钥
服务器属于个人的,需要一定的权限才能自由上传图片,这个负责权限验证的其实就是秘钥。拥有秘钥是进行上传的基础条件。
密钥配置
API密钥管理
安全性提示
实际工作中,秘钥属于敏感信息,不能直接放到前端存储,容易产生安全问题,更好的做法是把秘钥交给后端管理,前端通过调用接口先获取秘钥,有了秘钥之后再进行上传操作
封装员工头像组件-整体说明
创建image-upload组件
<template>
<el-upload
class="avatar-uploader"
action=""
:show-file-list="false"
:before-upload="beforeAvatarUpload"
>
<!-- (自动上传)action是上传地址 人资项目不需要 人资项目(手动上传) -->
<!-- show-file-list不展示列表 -->
<img v-if="value" :src="value" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon" />
</el-upload>
</template>
<script>
export default {
props: {
value: {
type: String,
default: ''
}
},
methods: {
// 检查函数 判断文件的类型还有大小 return true(继续上传)/false(停止上传)
beforeAvatarUpload(file) {
// jpeg png gif bmp
const isJPG = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
const isLt2M = file.size / 1024 / 1024 < 5 // 5M
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG PNG GIF BMP 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 5MB!')
}
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>
在父组件中应用
<image-upload v-model="userInfo.staffPhoto" />
使用cos-sdk完成上传
安装腾讯云js-sdk
$ npm i cos-js-sdk-v5
$ yarn add cos-js-sdk-v5
使用el-upload自定义上传
<template>
<el-upload
class="avatar-uploader"
action=""
:show-file-list="false"
:before-upload="beforeAvatarUpload"
:http-request="uploadImage"
>
<!-- (自动上传)action是上传地址 http-request(手动上传) -->
<!-- show-file-list不展示列表 -->
<img v-if="value" :src="value" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon" />
</el-upload>
</template>
实现上传方法
// 选择图片上传
uploadImage(params) {
console.log(params.file)
const cos = new COS({
SecretId: '',
SecretKey: ''
}) // 完成cos对象的初始化
cos.putObject({
Bucket: '', // 存储桶名称
Region: 'ap-nanjing', // 地域名称
Key: params.file.name, // 文件名称
StorageClass: 'STANDARD', // 固定值
Body: params.file // 文件对象
}, (err, data) => {
if (data.statusCode === 200 && data.Location) {
// 拿到了腾讯云返回的地址
// 通过input自定义事件将地址传出去
this.$emit('input', 'http://' + data.Location) // 将地址返回了
} else {
this.$message.error(err.Message) // 上传失败提示消息
}
})
}
这里需要使用 上面准备好的存储桶的名称-地域名称-应用标识-应用密钥
在下图所示拿到密匙 SecretId: '',
SecretKey: ''