Troubleshooting issue with VUE JS: Unable to reset preview image after uploading file

After successfully uploading an image and resetting the preview image and input file field, I encounter an issue where selecting another image does not display the preview. To address this, I set the variable that is bound to the image source to an empty string ('').

Here is the upload function:

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);
        })

The following is the HTML form. You can see v-bind:src="imageData" which I am resetting in the upload function. The image-preview HTML is just disappearing after the upload.

<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>

The preview image function:

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]);
        }
    },

Answer №1

There's an issue in the following code snippet - when you use jQuery-clone to clean up the input, you end up losing all the event bindings for that element, causing the previewImage method to no longer be triggered:

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

Instead of using jQuery, consider implementing the solution with vue.js:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for creating a "this" function

How can I optimize my JavaScript code using variables or "this"? It feels like there is too much code for such a simple intention. $("#Linkitem1").click(function() { $("#item1").fadeIn(2500); $("#item2, #item3").hide(); $(".active.btn-warning").re ...

ReactJS component's function become operational only after double tapping

Dealing with the asynchronous nature of react hook updates can be a common challenge. While there are similar questions out there, I'm struggling to find a solution for my specific case. The issue arises when trying to add a new product object into a ...

Using jQuery Mobile: Implementing listview data-filter for multiple data sets

I'm working on a JQM page with two data-role="listview" elements. Both of them are using the same data set, but one listview displays only text while the other includes icons as well. My goal is to implement the data-filter="true" option for both lis ...

Jest's expect.any(Object) function is not able to match CancelToken

After converting some files in a project to TypeScript, I encountered a test failure related to the following code: expect(mocks.request).toHaveBeenCalledWith({ headers: { 'Content-Type': 'bar' }, method: 'put', params: ...

Changing the Structure of a JSON Data Object

After using Papa Parse to generate a JSON from a CSV file, the structure of the JSON appears as follows: { object, object, object, .... , object } Now, I have a requirement to transform this JSON into the following format: { "publication" : { ...

Using Rails: How can I insert form data upon clicking?

In my Rails application, I have a basic form for shipping details: <% form_for shipping_object do |f| %> <%= f.text_field :address1, :placeholder => "Address Line 1*", :class => "forms" %><br/> <%= f.text_field :address2, :place ...

Ways to bring in a Typescript Vue project to a Javascript Vue

I am trying to incorporate this Calendar component into my Javascript Vue 3 project. To achieve this, I have created a new component in my project named ProCalendar.vue and copied the code from the example found in App.vue. Additionally, I have added the n ...

I am currently grappling with a JavaScript mouse over event and encountering some difficulties

I am looking to dynamically change the background image of my body div whenever a link is hovered over. Here is a snippet of my code: JAVASCRIPT: var i = 0, anchors = document.querySelectorAll("zoom"), background = document.getElementById("body") ...

What could be causing the created method to malfunction in vue-resources?

I am new to Vue.js and recently installed Vue resources following these steps: npm install vue-resources --save in main.js: import VueResource from 'vue-resource' in main.js: Vue.use(VueResource); App.vue: <template> <d ...

Guide to looping through an array within an object in React JS

Let's imagine we have an array of objects like this: const chefs = [ { key: 1, images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/&apo ...

The combination of Node.js module.exports and shorthand ternary operators for conditional statements

Can you explain the purpose of this line 'undefined' != typeof User ? User : module.exports and why is everything enclosed within (function(){})? I am having trouble understanding its significance. This code snippet is extracted from a library f ...

Unable to retrieve the size of the dynamically generated array within the ngOnInit() lifecycle hook in Angular

Recently, I encountered an issue where I couldn't retrieve the length of a dynamically generated array in my Angular application's ngOnInit() method. @Component({ selector: 'rise-our-champions', templateUrl: './our-champions.c ...

Having trouble with the alias in commander.js not functioning as desired when using the "--help" option

Currently, I am facing a strange issue while working on my project with commander.js. The problem arises when assigning an alias for a command. I looked at some examples mentioned in the reference: Commander.JS Example I decided to create a git-like comma ...

Can you explain the significance of the error message stating "XMLHttpRequest.timeout cannot be set for synchronous http(s) requests made from the window context"?

I'm experiencing some timeouts with a synchronous XML HTTP request in Safari on my Mac. In an attempt to fix this issue, I added a timeout setting like this: req.open(this.method, fullURL, this.isAsync); req.setRequestHeader('Content-Typ ...

Extract certain text from an element using a straightforward script

Is there a way to simplify this JavaScript code for splitting specific text from an element? Here is an example of the HTML element: <div id="ReviewBox"> <span>(By:) Hello</span> <div id="ReviewBox"> <span>By: Goodbye</ ...

Performance challenges with an AngularJS application that uses pagination

Resolving Performance Issues in Paginated AngularJS Posts Application I developed a compact application that showcases JSON data as cards using AngularJS and Twitter Bootstrap 4. The app includes pagination with approximately 100 posts per page. var ro ...

What are some ways to utilize Windows GDI functions in .NET that are not available in GDI+?

I need assistance in accessing a GDI method that seems to be missing in GDI+ within my .NET application. Specifically, I am looking for information on this particular method which retrieves kerning pairs for a specified font. My goal is to incorporate ker ...

The activity.from object in the messageReaction is lacking the name property

During my testing of an MS Teams bot, I have incorporated the onReactionsAdded event as shown below. this.onReactionsAdded(async (context, next) => { var name=context.activity.from.name; . . . } However, it seems that the name property ...

Vue component is showing undefined when attempting to run app.config

The contents of my main.js file in the app are as follows: import { createApp } from 'vue' import App from './App.vue' import router from './router' const app = createApp(App) const globalProps = app.config.globalProperties ...

When using node.js with express, the req.on('end') event is triggered, but the req.on('data') event does not fire

When using body parser, you have the option of either: application/x-www-form-urlencoded body parser or json body parser Both options yield the same results. This is how the API is being called: $.ajax({ type:'post', url:'/ ...