【问题标题】:VueJS file upload not accepting fileVueJS文件上传不接受文件
【发布时间】:2019-01-31 05:05:08
【问题描述】:

我正在使用 VueJS 进行文件上传图像预览,但我遇到了一个问题... 1. - 文件由用户上传 2. - 预览出现在输入字段旁边 3. - 现在输入框显示虽然有预览但没有上传图片。

这里是html:

<input type='file' accept='image/*' @change="onChange" name='file'  />
<img width='200' :src="uploadPreview" alt='preview' />

这是我的 vueJs 代码:

    data: function() { return {
        uploadPreview : "",
        }
    },
    methods : {
        onChange(e) {
            if (! e.target.files.length) return;

            let file = e.target.files[0];

            let reader = new FileReader();

            reader.readAsDataURL(file);
            reader.onload = e => {
                this.uploadPreview = e.target.result; // if this line is commented out or just not present, the upload will work but the preview won't show since uploadPreview does not have a value set.
                };
            },
     }

我在那里的代码中评论了该行的某些内容。
this.uploadPreview = e.target.result;
如果此行被注释掉或不存在,则上传将起作用,但不会显示预览,因为 uploadPreview 没有设置值。

为什么这不起作用?为什么简单地将uploadPreview设置为一些二进制图像数据后,文件的输入字段值会重置???再一次把我的头撞在这张桌子上。

【问题讨论】:

    标签: vue.js file-upload


    【解决方案1】:

    我建议你调试点。试着告诉我。

    data: function() { return {
            uploadPreview : "ABCD",
            }
        },
        methods : {
            onChange(e) {
                if (! e.target.files.length) return;
    
                let file = e.target.files[0];
    
                let reader = new FileReader();
    
                reader.readAsDataURL(file);
                reader.onload = e => {
            console.log("FIRST SEE WHAT'S INSIDE THE RESULTS",e.target.result);
            console.log("SECOND MAKE SURE YOU CAN ACCESS",this.uploadPreview) // this should print ABCD
                    this.uploadPreview = e.target.result; // if this line is commented out or just not present, the upload will work but the preview won't show since uploadPreview does not have a value set.
                    };
                },
         }
    

    最后

    <img width='200' :src="uploadPreview" :alt='uploadPreview' />
    

    (alt应该等于图片数据)

    【讨论】:

    • 已经试过了,将之前和之后的值记录到控制台,一切都检查出来了。 file 保持相同的对象,e.target.result 保持不变,this.uploadPreview 与结果相同。
    • 复制您为 uploadPreview 获得的内容并将其粘贴为您的 src,不带分号。看到复制的字符串可以正确输出图片了吗?
    猜你喜欢
    • 2012-10-02
    • 2012-05-12
    • 1970-01-01
    • 2015-12-30
    • 2014-02-17
    • 2012-01-05
    • 2019-03-03
    • 1970-01-01
    • 2023-01-30
    相关资源
    最近更新 更多