View uploaded images using JS
BoPeng opened this issue · 1 comments
Instead of showing the filenames of uploaded images, I would like to display a preview of images. This can be done for already uploaded files since I can pass the URLs of uploaded images as metadata
and create the needed img
by listening to the addUpload
event. The code to achieve this is something like
const eventEmitter = new EventEmitter3();
eventEmitter.on(
"addUpload",
({ element, fieldName, metaDataField, fileName, upload }) => {
if (!metaDataField || !metaDataField.value) {
return;
}
const metadata = JSON.parse(metaDataField.value);
// add thumbnail
const thumbnailElem = document.createElement('img');
thumbnailElem.src = metadata[fileName]['url'];
element.insertBefore(thumbnailElem, element.firstElementChild.nextElementSibling);
}}
);
The challenge is how to view the content of an image file after it is uploaded. This can depend on the type of uploader (e.g. S3 or not) but can be done if the content of the file is in memory. For example, after uploading some (small) images to S3, the upload object holds chunks
, which can hold the entire image if the image is small enough.
I am therefore thinking of something like
const eventEmitter = new EventEmitter3();
eventEmitter.on(
"uploadComplete",
({ element, fieldName, metaDataField, fileName, upload }) => {
console.log(upload);
const thumbnailElem = document.createElement('img');
thumbnailElem.src = ????
element.insertBefore(thumbnailElem, element.firstElementChild.nextElementSibling);
}
}
);
The remaining issue is how to create the content of the image from data available in the upload
object, and this is where I get stuck. Does anyone have any idea how to proceed?
Google showed me this stackoverflow post and I am amazed that
var urlCreator = window.URL || window.webkitURL;
thumbnailElem.src = urlCreator.createObjectURL(upload.chunks[0]);
works!
Of course this works only for S3 uploader and only when there is only one trunk of data, but I am still happy that image preview works in some, if not most of my use cases.
@mbraak can close the ticket if you do not have anything to add.