From 9dec7ba7e9edc905b121d2aa6f6d0922ef4121b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Theys?= Date: Mon, 20 May 2019 14:12:38 +0000 Subject: [IMP] web, *: add utils to get dataURL (base64) from file/blob * = partner_autocomplete, point_of_sale, web_editor, website_forum, website_slides This can be used for example to preview an image from a file input field. It can also be used to send the base64 content of the input by RPC instead of having to rely on form submit as POST with multipart/form-data. Technically wrap FileReader.readAsDataURL in a Promise. This will also be used in task-1930726 PR: #33508 Signed-off-by: Quentin Smetz (qsm) --- addons/web/static/src/js/core/utils.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'addons/web/static/src/js/core/utils.js') diff --git a/addons/web/static/src/js/core/utils.js b/addons/web/static/src/js/core/utils.js index 44e09933a25..44e17324b85 100644 --- a/addons/web/static/src/js/core/utils.js +++ b/addons/web/static/src/js/core/utils.js @@ -278,6 +278,28 @@ var utils = { } return ""; }, + /** + * Gets dataURL (base64 data) from the given file or blob. + * Technically wraps FileReader.readAsDataURL in Promise. + * + * @param {Blob|File} file + * @returns {Promise} resolved with the dataURL, or rejected if the file is + * empty or if an error occurs. + */ + getDataURLFromFile: function (file) { + if (!file) { + return Promise.reject(); + } + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.addEventListener('load', function () { + resolve(reader.result); + }); + reader.addEventListener('abort', reject); + reader.addEventListener('error', reject); + reader.readAsDataURL(file); + }); + }, /** * Returns a human readable number (e.g. 34000 -> 34k). * -- cgit v1.2.3