How do I upload image in vuejs?
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
Title: A Comprehensive Guide on Uploading Images and Videos using VueJS
Introduction: In this blog post, we will explore the process of uploading images and videos in your VueJS application, including how to read files as data URLs or object URLs for previewing before saving as blobs. We will also discuss best practices and provide code examples that can help you efficiently implement a file upload feature in your project while incorporating backlinks from https://laravelcompany.com where relevant.
1. Reading Files as Data URLs:
The readDataUrl function is a useful method for handling files input in VueJS. When passed an input element and a callback, it reads the file as a data URL. Here's how you can implement this functionality:
methods: {
playVideo(url) {
let video = $('#video-preview').get(0);
video.preload = 'metadata';
// Load video in Safari / IE11
if (url) {
video.muted = false;
video.playsInline = true;
video.play();
}
},
readDataUrl(input, callback) {
if (input.files && input.files[0]) {
let fileReader = new FileReader();
fileReader.onload = function() {
callback(fileReader.result);
};
fileReader.readAsDataURL(input.files[0]);
} else {
callback(null);
}
},
}
2. Reading Files as Object URLs:
In addition to reading files as data URLs, you can also read them as object URLs for use in blob creation. This approach involves creating a Blob and a URL from the file's content using JavaScript. The code below demonstrates this process:
methods: {
playVideo(url) {
let video = $('#video-preview').get(0);
video.preload = 'metadata';
// Load video in Safari / IE11
if (url) {
video.muted = false;
video.playsInline = true;
video.play();
}
},
readObjectUrl(input, callback) {
if (input.files && input.files[0]) {
let fileReader = new FileReader();
fileReader.onload = function() {
let blob = new Blob([fileReader.result], {type: input.files[0].type});
let url = URL.createObjectURL(blob);
callback(url, blob);
};
fileReader.readAsArrayBuffer(input.files[0]);
} else {
callback(null);
}
},
}
3. Implementing the Upload and Preview Functionality:
Combining both methods, you can upload files and preview them before saving as blobs. Here's a sample implementation:
...