simpleuploadadapter.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module upload/adapters/simpleuploadadapter
  7. */
  8. /* globals XMLHttpRequest, FormData, console */
  9. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  10. import FileRepository from '../filerepository';
  11. import { attachLinkToDocumentation } from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  12. /**
  13. * The Simple upload adapter allows uploading images to an application running on your server using
  14. * the [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) API with a
  15. * minimal {@link module:upload/adapters/simpleuploadadapter~SimpleUploadConfig editor configuration}.
  16. *
  17. * ClassicEditor
  18. * .create( document.querySelector( '#editor' ), {
  19. * simpleUpload: {
  20. * uploadUrl: 'http://example.com',
  21. * headers: {
  22. * ...
  23. * }
  24. * }
  25. * } )
  26. * .then( ... )
  27. * .catch( ... );
  28. *
  29. * See the {@glink features/image-upload/simple-upload-adapter "Simple upload adapter"} guide to learn how to
  30. * learn more about the feature (configuration, server–side requirements, etc.).
  31. *
  32. * Check out the {@glink features/image-upload/image-upload comprehensive "Image upload overview"} to learn about
  33. * other ways to upload images into CKEditor 5.
  34. *
  35. * @extends module:core/plugin~Plugin
  36. */
  37. export default class SimpleUploadAdapter extends Plugin {
  38. /**
  39. * @inheritDoc
  40. */
  41. static get requires() {
  42. return [ FileRepository ];
  43. }
  44. /**
  45. * @inheritDoc
  46. */
  47. static get pluginName() {
  48. return 'SimpleUploadAdapter';
  49. }
  50. /**
  51. * @inheritDoc
  52. */
  53. init() {
  54. const options = this.editor.config.get( 'simpleUpload' );
  55. if ( !options ) {
  56. return;
  57. }
  58. if ( !options.uploadUrl ) {
  59. /**
  60. * The {@link module:upload/adapters/simpleuploadadapter~SimpleUploadConfig#uploadUrl `config.simpleUpload.uploadUrl`}
  61. * configuration required by the {@link module:upload/adapters/simpleuploadadapter~SimpleUploadAdapter `SimpleUploadAdapter`}
  62. * is missing. Make sure the correct URL is specified for the image upload to work properly.
  63. *
  64. * @error simple-upload-adapter-missing-uploadUrl
  65. */
  66. console.warn( attachLinkToDocumentation(
  67. 'simple-upload-adapter-missing-uploadUrl: Missing the "uploadUrl" property in the "simpleUpload" editor configuration.'
  68. ) );
  69. return;
  70. }
  71. this.editor.plugins.get( FileRepository ).createUploadAdapter = loader => {
  72. return new Adapter( loader, options );
  73. };
  74. }
  75. }
  76. /**
  77. * Upload adapter.
  78. *
  79. * @private
  80. * @implements module:upload/filerepository~UploadAdapter
  81. */
  82. class Adapter {
  83. /**
  84. * Creates a new adapter instance.
  85. *
  86. * @param {module:upload/filerepository~FileLoader} loader
  87. * @param {module:upload/adapters/simpleuploadadapter~SimpleUploadConfig} options
  88. */
  89. constructor( loader, options ) {
  90. /**
  91. * FileLoader instance to use during the upload.
  92. *
  93. * @member {module:upload/filerepository~FileLoader} #loader
  94. */
  95. this.loader = loader;
  96. /**
  97. * The configuration of the adapter.
  98. *
  99. * @member {module:upload/adapters/simpleuploadadapter~SimpleUploadConfig} #options
  100. */
  101. this.options = options;
  102. }
  103. /**
  104. * Starts the upload process.
  105. *
  106. * @see module:upload/filerepository~UploadAdapter#upload
  107. * @returns {Promise}
  108. */
  109. upload() {
  110. return this.loader.file
  111. .then( file => new Promise( ( resolve, reject ) => {
  112. this._initRequest();
  113. this._initListeners( resolve, reject, file );
  114. this._sendRequest( file );
  115. } ) );
  116. }
  117. /**
  118. * Aborts the upload process.
  119. *
  120. * @see module:upload/filerepository~UploadAdapter#abort
  121. * @returns {Promise}
  122. */
  123. abort() {
  124. if ( this.xhr ) {
  125. this.xhr.abort();
  126. }
  127. }
  128. /**
  129. * Initializes the `XMLHttpRequest` object using the URL specified as
  130. * {@link module:upload/adapters/simpleuploadadapter~SimpleUploadConfig#uploadUrl `simpleUpload.uploadUrl`} in the editor's
  131. * configuration.
  132. *
  133. * @private
  134. */
  135. _initRequest() {
  136. const xhr = this.xhr = new XMLHttpRequest();
  137. xhr.open( 'POST', this.options.uploadUrl, true );
  138. xhr.responseType = 'json';
  139. }
  140. /**
  141. * Initializes XMLHttpRequest listeners
  142. *
  143. * @private
  144. * @param {Function} resolve Callback function to be called when the request is successful.
  145. * @param {Function} reject Callback function to be called when the request cannot be completed.
  146. * @param {File} file Native File object.
  147. */
  148. _initListeners( resolve, reject, file ) {
  149. const xhr = this.xhr;
  150. const loader = this.loader;
  151. const genericErrorText = `Couldn't upload file: ${ file.name }.`;
  152. xhr.addEventListener( 'error', () => reject( genericErrorText ) );
  153. xhr.addEventListener( 'abort', () => reject() );
  154. xhr.addEventListener( 'load', () => {
  155. const response = xhr.response;
  156. if ( !response || response.error ) {
  157. return reject( response && response.error && response.error.message ? response.error.message : genericErrorText );
  158. }
  159. resolve( response.url ? { default: response.url } : response.urls );
  160. } );
  161. // Upload progress when it is supported.
  162. /* istanbul ignore else */
  163. if ( xhr.upload ) {
  164. xhr.upload.addEventListener( 'progress', evt => {
  165. if ( evt.lengthComputable ) {
  166. loader.uploadTotal = evt.total;
  167. loader.uploaded = evt.loaded;
  168. }
  169. } );
  170. }
  171. }
  172. /**
  173. * Prepares the data and sends the request.
  174. *
  175. * @private
  176. * @param {File} file File instance to be uploaded.
  177. */
  178. _sendRequest( file ) {
  179. // Set headers if specified.
  180. const headers = this.options.headers || {};
  181. // Use the withCredentials flag if specified.
  182. const withCredentials = this.options.withCredentials || false;
  183. for ( const headerName of Object.keys( headers ) ) {
  184. this.xhr.setRequestHeader( headerName, headers[ headerName ] );
  185. }
  186. this.xhr.withCredentials = withCredentials;
  187. // Prepare the form data.
  188. const data = new FormData();
  189. data.append( 'upload', file );
  190. // Send the request.
  191. this.xhr.send( data );
  192. }
  193. }
  194. /**
  195. * The configuration of the {@link module:upload/adapters/simpleuploadadapter~SimpleUploadAdapter simple upload adapter}.
  196. *
  197. * ClassicEditor
  198. * .create( editorElement, {
  199. * simpleUpload: {
  200. * // The URL the images are uploaded to.
  201. * uploadUrl: 'http://example.com',
  202. *
  203. * // Headers sent along with the XMLHttpRequest to the upload server.
  204. * headers: {
  205. * ...
  206. * }
  207. * }
  208. * } );
  209. * .then( ... )
  210. * .catch( ... );
  211. *
  212. * See the {@glink features/image-upload/simple-upload-adapter "Simple upload adapter"} guide to learn more.
  213. *
  214. * See {@link module:core/editor/editorconfig~EditorConfig all editor configuration options}.
  215. *
  216. * @interface SimpleUploadConfig
  217. */
  218. /**
  219. * The configuration of the {@link module:upload/adapters/simpleuploadadapter~SimpleUploadAdapter simple upload adapter}.
  220. *
  221. * Read more in {@link module:upload/adapters/simpleuploadadapter~SimpleUploadConfig}.
  222. *
  223. * @member {module:upload/adapters/simpleuploadadapter~SimpleUploadConfig} module:core/editor/editorconfig~EditorConfig#simpleUpload
  224. */
  225. /**
  226. * The path (URL) to the server (application) which handles the file upload. When specified, enables the automatic
  227. * upload of resources (images) inserted into the editor content.
  228. *
  229. * Learn more about the server application requirements in the
  230. * {@glink features/image-upload/simple-upload-adapter#server-side-configuration "Server-side configuration"} section
  231. * of the feature guide.
  232. *
  233. * @member {String} module:upload/adapters/simpleuploadadapter~SimpleUploadConfig#uploadUrl
  234. */
  235. /**
  236. * An object that defines additional [headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) sent with
  237. * the request to the server during the upload. This is the right place to implement security mechanisms like
  238. * authentication and [CSRF](https://developer.mozilla.org/en-US/docs/Glossary/CSRF) protection.
  239. *
  240. * ClassicEditor
  241. * .create( editorElement, {
  242. * simpleUpload: {
  243. * headers: {
  244. * 'X-CSRF-TOKEN': 'CSRF-Token',
  245. * Authorization: 'Bearer <JSON Web Token>'
  246. * }
  247. * }
  248. * } );
  249. * .then( ... )
  250. * .catch( ... );
  251. *
  252. * Learn more about the server application requirements in the
  253. * {@glink features/image-upload/simple-upload-adapter#server-side-configuration "Server-side configuration"} section
  254. * of the feature guide.
  255. *
  256. * @member {Object.<String, String>} module:upload/adapters/simpleuploadadapter~SimpleUploadConfig#headers
  257. */
  258. /**
  259. * This flag enables the
  260. * [`withCredentials`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials)
  261. * property of the request sent to the server during the upload. It affects cross-site requests only and, for instance,
  262. * allows credentials such as cookies to be sent along with the request.
  263. *
  264. * ClassicEditor
  265. * .create( editorElement, {
  266. * simpleUpload: {
  267. * withCredentials: true
  268. * }
  269. * } );
  270. * .then( ... )
  271. * .catch( ... );
  272. *
  273. * Learn more about the server application requirements in the
  274. * {@glink features/image-upload/simple-upload-adapter#server-side-configuration "Server-side configuration"} section
  275. * of the feature guide.
  276. *
  277. * @member {Boolean} [module:upload/adapters/simpleuploadadapter~SimpleUploadConfig#withCredentials=false]
  278. */