首页 > 解决方案 > 文件上传后VUE JS预览图像重置不起作用

问题描述

当使用文件输入选择图像时,我的图像预览工作。然后我上传图像并重置预览图像和输入文件字段,因为它们需要在文件上传后重置。然后当我选择另一个图像时,该图像的预览不起作用。我正在做的是将其绑定到的变量图像 src 设置为''。

以下是上传功能

upload: function(){

        //Initialize the form data
        let formData = new FormData();

        //Add the form data we need to submit
        formData.append('file', this.imagefile);
        formData.append('journal_id', this.$route.params.id);

        //Make the request to the POST /single-file URL
        axios.post('/journal_charts/upload', formData)
        .then(response => {
            console.log('SUCCESS!');
            //reset the file input to null
            var input = $("#file");
            input.replaceWith(input.val('').clone(true));

            ** //reset the preview image to ''. This basically removes the image tag completely
            this.imageData = ''; **

            this.callGetChartList(this.$route.params.id);
        })

以下是 HTML 表单。您可以在上传功能中看到我正在重置的 v-bind:src="imageData" 。图片预览 HTML 只是在上传后消失

<input type="file" id="file" ref="file" name="file" class="btn-file" 
@change="previewImage" accept="image/*">
        <div class="image-preview row" v-if="imageData.length > 0">
            <div class="img-wrapper">
                <img class="image ml-md-3" v-bind:src="imageData">
            </div>

        </div>
        <div class="row">
            <button class="ml-md-3" @click="upload">Upload Chart</button>
        </div>

预览图像功能

previewImage: function(event) {
        // Reference to the DOM input element
        var input = event.target;
        // Ensure that you have a file before attempting to read it
        if (input.files && input.files[0]) {
            // create a new FileReader to read this image and convert to base64 format
            var reader = new FileReader();
            // Define a callback function to run, when FileReader finishes 
            its job
            reader.onload = (e) => {
                // Note: arrow function used here, so that "this.imageData" 
                refers to the imageData of Vue component
                // Read image as base64 and set to imageData
                this.imageData = e.target.result;
                this.imagefile = input.files[0];
            }
            // Start the reader job - read file as a data url (base64 format)
            reader.readAsDataURL(input.files[0]);
        }
    },

标签: javascriptvue.js

解决方案


input问题出在下一段代码中 - 当您在 jQuery 克隆的帮助下清理时,您会丢失该元素的所有事件绑定,并且previewImage不再调用该方法:

// reset the file input to null
var input = $("#file");
input.replaceWith(input.val('').clone(true));

所以尝试vue.js不使用 jQuery 的方法:

this.$refs.file.value = '';

[ https://jsfiddle.net/u9rfmhwL/ ]


推荐阅读