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