This question already has an answer here:
I am using Vue and need the files to preview before upload, if file is image then reduce its size (using canvas) and display, else just display the extension of file using canvas, so I have done something like this:
// I have used this function in the html like <img src={{ imagePreviewURL(File) }} />
imagePreviewURL(File) { // <-- get the uploaded file
const canvas = document.createElement('canvas')!; // <-- create canvas
const ctx = canvas.getContext('2d')!;
canvas.width = 100;
canvas.height = 100;
if (File.type.includes('image')) { // <-- if file is image
const image = new Image(); // <-- create new image
image.onload = () => {
ctx.drawImage(image, 100, 100); // <-- draw image to canvas
};
image.src = URL.createObjectURL(File); // <-- set source of image
} else {
ctx.font = '30px Arial';
ctx.textAlign = 'center';
ctx.fillText(`.${File.name.split('.').pop()!}`, 50, 55); // <-- just display extension
}
return ctx.canvas.toDataURL(); // <-- convert canvas to image
}
The extension part works very fine, but the image is not showing.