//html
<el-form-item label="上传文件" :label-width="formLabelWidth" prop="files">
<el-upload
class="upload-demo"
ref="upload"
:action="`${baseUrl}/agent/upFile`"
:headers="headers"
:on-success="uploadFile"
>
<el-button size="small">
<i class="el-icon-upload el-icon--left"></i>点击上传
</el-button>
</el-upload>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="add('ruleForm')" style="width:100%">提交</el-button>
</el-form-item>
//js
<script>
export default {
name: "Blank",
data() {
return {
form: {
title: null,
files: [],
headers: { Authorization: Auth.getToken() }, //token
},
baseUrl: null
};
},
// 上传图片成功的钩子
uploadFile(res) {
this.form.files.push(res.data)
},
// 添加
add(formName) {
this.$refs[formName].validate(valid => {
if (valid) {
let params = {
files: this.form.files,
title: this.form.title
}
uploadContract(params).then(res => {
this.dialogFormVisible = false
this.form = {
title: null,
date: []
}
// 清空已上传的文件列表
this.$refs.upload.clearFiles()
})
} else {
return false
}
})
},
mounted() {
this.baseUrl = process.env.VUE_APP_BASE_API
}
};
</script>
vue element upload图片 转换成base64
beforeUpload (file) {
var _this = this;
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
// 图片base64化
var newUrl = this.result; //图片路径
_this.imgUrl = newUrl;
};
},
//或者 不使用element-ui中 upload的自动上传的话 可以在on-change事件里面 转换成base64的路径
handleChange (file, fileList, item) {
this.getBase64(file.raw).then(res => {
console.log(res);
});
},
getBase64(file) {
return new Promise(function(resolve, reject) {
let reader = new FileReader();
let imgResult = "";
reader.readAsDataURL(file);
reader.onload = function() {
imgResult = reader.result;
};
reader.onerror = function(error) {
reject(error);
};
reader.onloadend = function() {
resolve(imgResult);
};
});
},
handleChange中 item是我的自定义参数
网友评论