html部份:
//img标签用于显示预览图片
<img :src="imageUrl" alt="" style="width: 300px;height: 80px;border: 1px dashed #ccc">
<div>
//input的name值是接口中的参数名
<input type="file" name="pic" ref="imgInput" @change="saveSrc()">
</div>
js部份
// 上传缩略图
uploadImgBtn() {
let form = new FormData($("#form")[0]);
let _this = this
$.ajax({
url: “请求地址",
type: "post",
data: form,
dataType: "json",
processData: false,
contentType: false,
async: false,
success: function (res) {
_this.form.picture = res.data
// console.log(res.data)
}
})
}
// 保存图片路径为base64,这一步是为了完成预览功能
saveSrc(e) {
let file = this.$refs.imgInput.files[0]
if (file === undefined) {
this.imageUrl = " "
console.log("没有选择图片")
}
const _this = this
let reader = new FileReader();
reader.readAsDataURL(file); // 读出 base64
reader.onloadend = function () {
_this.imageUrl = reader.result;
};
this.uploadImgBtn()
}