超简单的 vue上传图片可预览(input file)

html部份:
input的name是接口中的参数名

 <img :src="imageUrl" alt="" style="width: 300px;height: 80px;border: 1px dashed #ccc">
 <div>
 	<input type="file" name="pic" ref="imgInput" @change="saveSrc()"style="margin-left: 10px;"><br/>
 </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 () {
                // let res = _this.convertBase64UrlToBlob(reader.result)
                _this.imageUrl = reader.result;
            };
            this.uploadImgBtn()
        },
发布了10 篇原创文章 · 获赞 0 · 访问量 317

猜你喜欢

转载自blog.csdn.net/half_sugar/article/details/102821520
今日推荐