-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
simpleuploadadapter.ts
220 lines (189 loc) · 5.84 KB
/
simpleuploadadapter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/**
* @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module upload/adapters/simpleuploadadapter
*/
/* globals XMLHttpRequest, FormData */
import { Plugin } from '@ckeditor/ckeditor5-core';
import FileRepository, { type UploadResponse, type FileLoader, type UploadAdapter } from '../filerepository';
import type { SimpleUploadConfig } from '../uploadconfig';
import { logWarning } from '@ckeditor/ckeditor5-utils';
/**
* The Simple upload adapter allows uploading images to an application running on your server using
* the [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) API with a
* minimal {@link module:upload/uploadconfig~SimpleUploadConfig editor configuration}.
*
* ```ts
* ClassicEditor
* .create( document.querySelector( '#editor' ), {
* simpleUpload: {
* uploadUrl: 'http://example.com',
* headers: {
* ...
* }
* }
* } )
* .then( ... )
* .catch( ... );
* ```
*
* See the {@glink features/images/image-upload/simple-upload-adapter "Simple upload adapter"} guide to learn how to
* learn more about the feature (configuration, server–side requirements, etc.).
*
* Check out the {@glink features/images/image-upload/image-upload comprehensive "Image upload overview"} to learn about
* other ways to upload images into CKEditor 5.
*/
export default class SimpleUploadAdapter extends Plugin {
/**
* @inheritDoc
*/
public static get requires() {
return [ FileRepository ] as const;
}
/**
* @inheritDoc
*/
public static get pluginName() {
return 'SimpleUploadAdapter' as const;
}
/**
* @inheritDoc
*/
public init(): void {
const options = this.editor.config.get( 'simpleUpload' );
if ( !options ) {
return;
}
if ( !options.uploadUrl ) {
/**
* The {@link module:upload/uploadconfig~SimpleUploadConfig#uploadUrl `config.simpleUpload.uploadUrl`}
* configuration required by the {@link module:upload/adapters/simpleuploadadapter~SimpleUploadAdapter `SimpleUploadAdapter`}
* is missing. Make sure the correct URL is specified for the image upload to work properly.
*
* @error simple-upload-adapter-missing-uploadurl
*/
logWarning( 'simple-upload-adapter-missing-uploadurl' );
return;
}
this.editor.plugins.get( FileRepository ).createUploadAdapter = loader => {
return new Adapter( loader, options );
};
}
}
/**
* Upload adapter.
*/
class Adapter implements UploadAdapter {
/**
* FileLoader instance to use during the upload.
*/
public loader: FileLoader;
/**
* The configuration of the adapter.
*/
public options: SimpleUploadConfig;
private xhr?: XMLHttpRequest;
/**
* Creates a new adapter instance.
*/
constructor( loader: FileLoader, options: SimpleUploadConfig ) {
this.loader = loader;
this.options = options;
}
/**
* Starts the upload process.
*
* @see module:upload/filerepository~UploadAdapter#upload
*/
public upload(): Promise<UploadResponse> {
return this.loader.file
.then( file => new Promise( ( resolve, reject ) => {
this._initRequest();
this._initListeners( resolve, reject, file! );
this._sendRequest( file! );
} ) );
}
/**
* Aborts the upload process.
*
* @see module:upload/filerepository~UploadAdapter#abort
*/
public abort(): void {
if ( this.xhr ) {
this.xhr.abort();
}
}
/**
* Initializes the `XMLHttpRequest` object using the URL specified as
* {@link module:upload/uploadconfig~SimpleUploadConfig#uploadUrl `simpleUpload.uploadUrl`} in the editor's
* configuration.
*/
private _initRequest(): void {
const xhr = this.xhr = new XMLHttpRequest();
xhr.open( 'POST', this.options.uploadUrl, true );
xhr.responseType = 'json';
}
/**
* Initializes XMLHttpRequest listeners
*
* @param resolve Callback function to be called when the request is successful.
* @param reject Callback function to be called when the request cannot be completed.
* @param file Native File object.
*/
private _initListeners(
resolve: ( result: UploadResponse ) => void,
reject: ( message?: string ) => void,
file: File
): void {
const xhr = this.xhr!;
const loader = this.loader;
const genericErrorText = `Couldn't upload file: ${ file.name }.`;
xhr.addEventListener( 'error', () => reject( genericErrorText ) );
xhr.addEventListener( 'abort', () => reject() );
xhr.addEventListener( 'load', () => {
const response = xhr.response;
if ( !response || response.error ) {
return reject( response && response.error && response.error.message ? response.error.message : genericErrorText );
}
const urls = response.url ? { default: response.url } : response.urls;
// Resolve with the normalized `urls` property and pass the rest of the response
// to allow customizing the behavior of features relying on the upload adapters.
resolve( {
...response,
urls
} );
} );
// Upload progress when it is supported.
/* istanbul ignore else -- @preserve */
if ( xhr.upload ) {
xhr.upload.addEventListener( 'progress', evt => {
if ( evt.lengthComputable ) {
loader.uploadTotal = evt.total;
loader.uploaded = evt.loaded;
}
} );
}
}
/**
* Prepares the data and sends the request.
*
* @param file File instance to be uploaded.
*/
private _sendRequest( file: File ): void {
// Set headers if specified.
const headers = this.options.headers || {};
// Use the withCredentials flag if specified.
const withCredentials = this.options.withCredentials || false;
for ( const headerName of Object.keys( headers ) ) {
this.xhr!.setRequestHeader( headerName, headers[ headerName ] );
}
this.xhr!.withCredentials = withCredentials;
// Prepare the form data.
const data = new FormData();
data.append( 'upload', file );
// Send the request.
this.xhr!.send( data );
}
}