From 3d1e33396f4c467a65039fe339a96f7c318b449b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nathana=C3=ABl=20Jourdane?= Date: Mon, 4 Mar 2019 17:10:11 +0100 Subject: [PATCH] [wip upload-image] Upload image when selecting it on browse-file window --- src/js/easymde.js | 76 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/src/js/easymde.js b/src/js/easymde.js index 7fdaeed..c7d2b47 100644 --- a/src/js/easymde.js +++ b/src/js/easymde.js @@ -188,7 +188,7 @@ function createImageInput(editor) { imageInput.style.opacity = 0; imageInput.addEventListener('change', function(event) { for(var i=0; i= 1024 && u < units.length); + return '' + bytes.toFixed(1) + units[u]; +} + +/** + * Upload an image to the server. + * + * Can be triggered by: + * - drag&drop; // TODO + * - copy-paste; // TODO + * - the browse-file window (opened when the user clicks on the *upload-image* icon). + * + * @param file {File} The image to upload as a HTML5 File object (https://developer.mozilla.org/en-US/docs/Web/API/File) + * @param options The EasyMDE options. + */ +function uploadImage(file, options) { + if (file.size >= options.imageMaxSize) { + var units = options.imageTexts.sizeUnits.split(','); + alert(options.text.errorImageTooBig + .replace('#image_name#', file.name) + .replace('#image_size#', humanFileSize(file.size, units)) + .replace('#image_max_size#', humanFileSize(options.imageMaxSize, units)) + ); + return; + } + + var formData = new FormData(); + formData.append('image', file); + var request = new XMLHttpRequest(); + request.open('POST', options.imageUploadEndpoint); + request.send(formData); + + request.onprogress = function (event) { + if (event.lengthComputable) { + // TODO: test with a big image on a remote web server + var progress = Math.round((event.loaded * 100) / event.total); + console.log('EasyMDE: image upload progress: ' + progress + '%'); + // TODO: show progress on status bar instead + } + }; + + request.onload = function () { + if(this.status === 200) { + console.log('image url: ' + window.location.origin + '/' + this.responseText); + } else { + console.log('EasyMDE: Error ' + this.status + ' while importing image: ' + this.statusText.toString()); + } + }; +} + // Merge the properties of one object into another. function _mergeProperties(target, source) { for (var property in source) { @@ -1380,6 +1445,12 @@ var blockStyles = { 'italic': '*', }; +var imageTexts = { + errorImageTooBig: 'Image #image_name# is too big (#image_size#).\n' + + 'Maximum file size is #image_max_size#.', + sizeUnits: 'b,Kb,Mb', +}; + /** * Interface of EasyMDE. */ @@ -1488,6 +1559,9 @@ function EasyMDE(options) { // import-image default configuration + options.uploadImage = options.uploadImage || false; + options.imageMaxSize = options.imageMaxSize || 1024*1024*2; + options.imageTexts = extend({}, imageTexts, options.imageTexts || {}); options.imageAccept = options.imageAccept || 'image/png, image/jpeg';