Skip to content

Instantly share code, notes, and snippets.

@kylefox
Created October 17, 2018 15:58
Show Gist options
  • Save kylefox/c09a7b738aacf088c2ec2b359ddcc5ea to your computer and use it in GitHub Desktop.
Save kylefox/c09a7b738aacf088c2ec2b359ddcc5ea to your computer and use it in GitHub Desktop.
Convert Base64 data URLs to File objects for Trix attachments
window.AttachmentUtils = (function() {
var BASE64_MARKER = ';base64,';
var Utils = {
// Takes a file size (in bytes) and returns a human-friendly string representation.
humanFileSize: function(size) {
if(size < 1) return "0 bytes";
// http://stackoverflow.com/a/20732091
var factor = 1000; // Technically it should be 1024, but looks like most apps use 1000...
var i = Math.floor( Math.log(size) / Math.log(factor) );
return ( size / Math.pow(factor, i) ).toFixed(1) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
},
// Does the given URL (string) look like a base64-encoded URL?
isDataURI: function(url) {
return url.split(BASE64_MARKER).length === 2;
},
// Converts a data URI string into a File object.
dataURItoFile: function(dataURI) {
if(!AttachmentUtils.isDataURI(dataURI)) { return false; }
// Format of a base64-encoded URL:
// data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYAAAAEOCAIAAAAPH1dAAAAK
var mime = dataURI.split(BASE64_MARKER)[0].split(':')[1];
var filename = 'dataURI-file-' + (new Date()).getTime() + '.' + mime.split('/')[1];
var bytes = atob(dataURI.split(BASE64_MARKER)[1]);
var writer = new Uint8Array(new ArrayBuffer(bytes.length));
for (var i=0; i < bytes.length; i++) {
writer[i] = bytes.charCodeAt(i);
}
return new File([writer.buffer], filename, { type: mime });
}
};
return Utils;
})();
$(function() {
$(document).on('trix-attachment-add', function(event) {
var attachment = event.originalEvent.attachment,
url = attachment.getURL();
// Convert data URLs to File objects.
if(!attachment.file && AttachmentUtils.isDataURI(url)) {
attachment.file = AttachmentUtils.dataURItoFile(url);
}
if(attachment.file) {
return uploadAttachment(attachment);
} else {
console.error('Could not upload attachment.');
console.error(attachment);
attachment.remove();
}
});
});
@aproberts01
Copy link

Thank you for this! This solution was exactly what I was looking for.

Copy link

ghost commented Feb 26, 2020

Nice gist, but I am having errors at uploadAttachment() method, uploadAttachment is not defined. Where is this method at and what's inside it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment