imageuploadcommand.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import FileRepository from '@ckeditor/ckeditor5-upload/src/filerepository';
  6. import Command from '@ckeditor/ckeditor5-core/src/command';
  7. import { insertImage, isImageAllowed } from '../image/utils';
  8. /**
  9. * @module image/imageupload/imageuploadcommand
  10. */
  11. /**
  12. * Image upload command.
  13. *
  14. * @extends module:core/command~Command
  15. */
  16. export default class ImageUploadCommand extends Command {
  17. /**
  18. * @inheritDoc
  19. */
  20. refresh() {
  21. this.isEnabled = isImageAllowed( this.editor.model );
  22. }
  23. /**
  24. * Executes the command.
  25. *
  26. * @fires execute
  27. * @param {Object} options Options for the executed command.
  28. * @param {File|Array.<File>} options.files The image file or an array of image files to upload.
  29. */
  30. execute( options ) {
  31. const editor = this.editor;
  32. const model = editor.model;
  33. const fileRepository = editor.plugins.get( FileRepository );
  34. model.change( writer => {
  35. const filesToUpload = Array.isArray( options.files ) ? options.files : [ options.files ];
  36. for ( const file of filesToUpload ) {
  37. uploadImage( writer, model, fileRepository, file );
  38. }
  39. } );
  40. }
  41. }
  42. // Handles uploading single file.
  43. //
  44. // @param {module:engine/model/writer~writer} writer
  45. // @param {module:engine/model/model~Model} model
  46. // @param {File} file
  47. function uploadImage( writer, model, fileRepository, file ) {
  48. const loader = fileRepository.createLoader( file );
  49. // Do not throw when upload adapter is not set. FileRepository will log an error anyway.
  50. if ( !loader ) {
  51. return;
  52. }
  53. insertImage( writer, model, { uploadId: loader.id } );
  54. }