Skip to content

Instantly share code, notes, and snippets.

@f1ames
Created November 29, 2018 08:29
Show Gist options
  • Save f1ames/7876b2a18d89d9eb5f9719e98dd60de3 to your computer and use it in GitHub Desktop.
Save f1ames/7876b2a18d89d9eb5f9719e98dd60de3 to your computer and use it in GitHub Desktop.
UrlReader CKEditor5
/**
* @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md.
*/
/**
* @module upload/urlreader
*/
/* globals window */
/**
* Wrapper over the native `UrlReader`.
*/
export default class UrlReader {
/**
* Creates an instance of the UrlReader.
*/
constructor() {
this._error = null;
this._reject = null;
}
/**
* Returns error that occurred during url featching.
*
* @returns {Error}
*/
get error() {
return this._error;
}
/**
* Reads the provided url.
*
* @param {String} url URL to be read.
* @returns {Promise} Returns a promise that will be resolved with the `File` instance with contents of a given url.
* The promise will be rejected in case of an error or when the reading process is aborted.
*/
read( url ) {
return new Promise( ( resolve, reject ) => {
this._reject = reject;
window.fetch( url )
.then( resource => resource.blob() )
.then( blob => {
const type = blob.type;
const filename = `file.${ type.split( '/' ).pop() }`;
const file = new window.File( [ blob ], filename, { type: blob.type } );
this._reject = null;
resolve( file );
} )
.catch( error => {
this._reject = null;
this._error = error;
reject( error );
} );
} );
}
/**
* Aborts url reader.
*/
abort() {
if ( this._reject ) {
this._reject();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment