After years of doing this common feature needed in every app today I've written a small Image utility object (which allows you to download images as Blob, convert images to base64, canvas, etc, resize image) and came up with this simple algorithm:
<input type="file"> to file uploadsinput._file property to store a Blob.input._file.input._fileinput._file = blobinput._file has higher priority then the original. If it is set, then upload it or input.files[0] instead which is an instance of Blob interface also.Sample code:
import { BunnyImage } from 'bunnyjs/src/file/image';
const imageURL = '...';
const fileInput = document.getElementById('photo_upload');
const form = document.getElementById('photo_form');
BunnyImage.getImage(imageURL).then(image => {
return BunnyImage.resizeImage(image, 800, 600);
}).then(image => {
fileInput._file = BunnyImage.imageToBlob(image);
});
form.addEventListener('submit', e => {
e.preventDefault();
const fd = new FormData;
const blob = fileInput._file ? fileInput._file : fileInput.files[0];
const postName = fileInput.getAttribute('name');
fd.append(postName, blob, 'picture.jpg');
const request = new XMLHttpRequest();
request.open("POST", form.getAttribute('action'));
request.send(fd);
});
All that algorithm soon will be a part of a new component in BunnyJS. If you liked an answer, please star project on GitHub and share it. If you will have any feedback, ideas, proposals or questions please let me know.