一、无需安装阿里云插件
1、后端需要返回阿里云的配置信息
2、前端vue代码实现
需要安装js-md5、axios插件
<el-upload
class="upload"
ref="upload"
action=""
:on-change="upload"
accept="image/png, image/jpeg, image/jpg"
:show-file-list="false"
:auto-upload="false"
>
</el-upload>
<img :src="imgUrl">
import axios from 'axios'
import md5 from 'js-md5'
data() {
return {
imgUrl: ''
}
},
methods: {
// 选择文件
upload(file) {
console.log('file--', file);
const isIMAGE = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
const isLt3M = file.raw.size / 1024 / 1024 < 3
if (!isIMAGE) {
this.showToast('请选择 jpg、png 格式的图片')
return false
}
if (!isLt3M) {
this.showToast('图片大小不能超过 3MB')
return false
}
const path = this.aliossConfig.dir + this.genPath(file)
this.aliOssUpload(this.aliossConfig, file, path).then(res => {
console.log('阿里云直传结果--', res);
if (res.path) {
this.imgUrl = res.path
} else {
this.$message.error('头像上传阿里云失败,请联系工作人员')
}
})
},
/** 阿里云直传 */
async aliOssUpload(config, file, path, process) {
// config:阿里云配置信息,path:文件名
let form = new FormData()
form.append('key', path)
form.append('OSSAccessKeyId', config.accessKey)
form.append('policy', config.policy)
form.append('signature', config.sign)
form.append('file', file)
const res = await axios({
url: config.upload_domain,
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
'Content-Disposition': 'attachment;filename='+ encodeURIComponent(file.name),
},
onUploadProgress: function (progressEvent) {
if(progressEvent.lengthComputable) {
let rate = progressEvent.loaded / progressEvent.total * 100
rate = rate.toFixed(3)
rate = parseFloat(rate)
process && process(rate,progressEvent.loaded,progressEvent.total)
}
},
withCredentials:false,
data: form,
})
let domain = config.domain.replace(/\/$/,'')
return {path: `${domain}/${path}`}
},
/** 文件名加密、随机数处理 */
genPath(file) {
let ext = file.name.match(/\.[^\.]+$/) || ''
if(ext) {
ext = ext[0]
}
let filename = md5((Math.random() * 10000000) + '') + ext
return filename
},
}
这里前端实现的方法,也要后端做一些配置,具体后端配置可以查看阿里云文档;
签名直传文档 https://help.aliyun.com/document_detail/31926.html?spm=a2c4g.267439.0.0.311c4b78YwyQuw