项目中需要上传文件,用的vue+elementUI,使用的上传组件是elementUI的el-upload组件,用到过的上传方式有两种
1.上传到阿里云,再把返回的连接给后端
2.以formdata的方式直接传给后端
现在介绍下这两种上传方式
1.上传阿里云
<el-upload
class="avatar-uploader"
:class="{disabled4:uploadDisabled4}"
list-type="picture-card"
action
:before-upload="beforeAvatarUpload"
:on-success="handleAvatarSuccess4"
:on-preview="handlePictureCardPreview4"
:on-remove="handleRemove4"
:http-request="upLoadFile4"
>
<i class="el-icon-plus"></i>
</el-upload>
upLoadFile4的方法如下,其中client 是OSS对象,里面的内容,accessKeyId、accessKeySecret、oss_path等是后端获得后,我通过API从后端调用的,最后通过client.put方法,将文件上传到阿里云,阿里云返回图片的地址,然后把地址通过API给后端。
这里注意的是action不能少,可以不填值,使用到http-request upload组件提供的自定义方法事件。
upLoadFile4(file) {
let client = new OSS({
endpoint: this.endpoint,
accessKeyId: this.accessKeyId,
accessKeySecret: this.accessKeySecret,
stsToken: this.securityToken,
bucket: this.bucket_name
});
let storeAs = this.oss_path + file.file.name;
client.put(storeAs, file.file).then(res => {
let imageUrl4 = {
path: res.name,
url: res.url
};
this.ruleForm.imageUrl4 = imageUrl4;
this.imageUrl4 = imageUrl4;
});
2.以formdata上传
template代码
<el-form
ref="regeditForm"
:model="regeditForm"
:inline="false"
>
<el-upload
multiple
style="width:350px"
class="upload-demo"
ref="upload"
:file-list="fileList"
:on-change="fileChange"
:on-exceed="handleExceed"
accept=".war"
action
:http-request="httpRequest"
:auto-upload="false"
:on-remove="handleRemove"
:before-remove="beforeRemove"
>
<el-button size="mini" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传war文件</div>
</el-upload>
</el-form-item>
<el-form-item style="text-align:left;width:430px">
<el-button type="primary" @click="register('regeditForm')">提交</el-button>
</el-form-item>
</el-form>
方法代码
httpRequest(param) {
console.log(this.fileList);
let fileObj = param.file; // 相当于input里取得的files
let data = new FormData(); // FormData 对象
data.append("file", fileObj); // 文件对象
data.append("name", this.regeditForm.name);
data.append("description", this.regeditForm.description);
data.append("url", this.regeditForm.url);
register(data).then(res => {
// console.log(res);
if (res.data.msg == "app上传成功") {
this.$alert("url地址是" + res.data.result, "部署成功", {
confirmButtonText: "确定",
callback: () => {}
});
}
});
},
register(formName) {
this.$refs[formName].validate(valid => {
if (valid) {
this.$refs.upload.submit();
} else {
console.log("error submit!!");
return false;
}
});
},
export function register(data) {
return request({
url: '/app/add',
method: 'post',
headers: {
'Content-Type': 'multipart/form-data'
},
data
})
}
这块的重点是1.this.$refs.upload.submit(); 2.FormData
1. 当在upload上添 http-request="httpRequest" 自定义方法时,点击表单提交的时候使用 this.$refs.upload.submit(); 会触发自定义的方法
2. new FormData() 实例化formData实例,使用append把数据添加进去
3. 接口请求定义头部的 'Content-Type': 'multipart/form-data'
