1.使用默认方式上传
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/" // 图片上传地址
:data="data"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
- action填写后端给的文件上传地址
- 如果接口需要传输其他参数,可以绑定到data上面, 比如data={token: "token"}
{
"error": 0,
"url": "",
"name": ""
}
2.自定义上传
- el-upload中添加属性:http-request="upload"绑定自定义的上传函数
<el-upload
:http-request="upload"
- 实现上传函数,这里使用xhr上传
upload(param) {
console.log('参数', param)
try {
// 创建form对象,必须使用这个,会自动把content-type设置成multi-part-form
const formData = new FormData()
formData.append('file', param.file)
//创建xhr
const xhr = new XMLHttpRequest()
//post上传地址
xhr.open('post', this.url)
//设置token如果需要
xhr.setRequestHeader('token', getToken())
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
const json = JSON.parse(xhr.response)
// 根据后端给的信息判断是否上传成功
if (json.code === 1) {
param.onSuccess(json, param.file, param.fileList)
this.fileList.push({ name: param.file.name, url: json.url, data: json.data })
} else {
param.onError(json)
}
}
}
//获取上传的进度
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var percent = event.loaded / event.total * 100
param.onProgress(percent)
}
}
//将formdata上传
xhr.send(formData)
} catch (e) {
param.onError(e)
}
},
3.上传到七牛,和2类似,把其中的xhr换成七牛上传即可