代码的大概逻辑是页面弹出 dialog 框显示上传组件,选择图片上传到服务器,服务器返回图片链接,在页面显示出图片,并可以提交表单保存到数据库。如果有兴趣可以尝试一下。
1、页面。
<el-dialog v-loading="uploadStatus"
element-loading-text="正在上传中"
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(0, 0, 0, 0)"
:title="title" :visible.sync="open" width="700px" append-to-body>
<el-form ref="form" :model="form" label-width="100px">
<el-form-item label="背景图" prop="background">
<el-row>
<el-col :span="10">
<el-image style="width: 120px; height: 80px"
:src="this.form.background"
:preview-src-list="[this.form.background]"></el-image>
</el-col>
<el-col :span="14">
<el-input v-model="this.form.background" :disabled="true" size="mini"/>
<el-upload
class="upload-demo"
action
:show-file-list="false"
:before-upload="beforeUploadImage"
list-type="picture"
:http-request="uploadBackgroundImage">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</el-col>
</el-row>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
2、js
export default {
data() {
return {
// 上传遮罩层
uploadStatus: false,
// 弹出层标题
title: "",
// 是否显示弹出层
open: false,
// 表单参数
form: {},
};
},
methods: {
// 取消按钮
cancel() {
this.open = false;
this.reset();
},
/** 提交按钮 */
submitForm: function () {
this.$refs["form"].validate(valid => {
// 省略保存代码
});
},
beforeUploadImage(file) {
let fileSuffix = 'jpg,jpeg,png';
let maxSize = 10000000;
let fileName = file.name;
if (fileSuffix.indexOf(fileName.substring(fileName.lastIndexOf(".") + 1)) < 0) {
this.$message({
showClose: true,
message: '图片类型错误, 只能是' + fileSuffix + '格式!',
type: 'error'
});
return false;
}
if (maxSize > 0 && file.size > maxSize) {
this.$message({
showClose: true,
message: '文件大小超过限定值!',
type: 'error'
});
return false;
}
return true;
},
},
uploadBackgroundImage(object) {
let typePath = "image";
let formData = new FormData();
let file = object.file;
this.uploadStatus = true;
formData.append("fileName", file.name);
formData.append("file", file);
formData.append("typePath", typePath);
upload(formData).then(response => {
this.uploadStatus = false;
this.$set(this.form, "background", response.data);
this.msgSuccess("上传成功");
});
},
}