2 * Provides an interface for uploading files to MediaWiki.
4 * @class mw.Api.plugin.upload
24 * Get nonce for iframe IDs on the page.
34 * Given a non-empty object, return one of its keys.
40 function getFirstKey( obj
) {
43 if ( obj
.hasOwnProperty( key
) ) {
50 * Get new iframe object for an upload.
54 * @return {HTMLIframeElement}
56 function getNewIframe( id
) {
57 var frame
= document
.createElement( 'iframe' );
64 * Shortcut for getting hidden inputs
67 * @param {string} name
71 function getHiddenInput( name
, val
) {
72 return $( '<input>' ).attr( 'type', 'hidden' )
78 * Process the result of the form submission, returned to an iframe.
79 * This is the iframe's onload event.
81 * @param {HTMLIframeElement} iframe Iframe to extract result from
82 * @return {Object} Response from the server. The return value may or may
83 * not be an XMLDocument, this code was copied from elsewhere, so if you
84 * see an unexpected return type, please file a bug.
86 function processIframeResult( iframe
) {
88 doc
= iframe
.contentDocument
|| frames
[ iframe
.id
].document
;
90 if ( doc
.XMLDocument
) {
91 // The response is a document property in IE
92 return doc
.XMLDocument
;
96 // Get the json string
97 // We're actually searching through an HTML doc here --
98 // according to mdale we need to do this
99 // because IE does not load JSON properly in an iframe
100 json
= $( doc
.body
).find( 'pre' ).text();
102 return JSON
.parse( json
);
105 // Response is a xml document
109 function formDataAvailable() {
110 return window
.FormData
!== undefined &&
111 window
.File
!== undefined &&
112 window
.File
.prototype.slice
!== undefined;
115 $.extend( mw
.Api
.prototype, {
117 * Upload a file to MediaWiki.
119 * The file will be uploaded using AJAX and FormData, if the browser supports it, or via an
120 * iframe if it doesn't.
122 * Caveats of iframe upload:
123 * - The returned jQuery.Promise will not receive `progress` notifications during the upload
124 * - It is incompatible with uploads to a foreign wiki using mw.ForeignApi
125 * - You must pass a HTMLInputElement and not a File for it to be possible
127 * @param {HTMLInputElement|File|Blob} file HTML input type=file element with a file already inside
128 * of it, or a File object.
129 * @param {Object} data Other upload options, see action=upload API docs for more
130 * @return {jQuery.Promise}
132 upload: function ( file
, data
) {
133 var isFileInput
, canUseFormData
;
135 isFileInput
= file
&& file
.nodeType
=== Node
.ELEMENT_NODE
;
137 if ( formDataAvailable() && isFileInput
&& file
.files
) {
138 file
= file
.files
[ 0 ];
142 throw new Error( 'No file' );
145 // Blobs are allowed in formdata uploads, it turns out
146 canUseFormData
= formDataAvailable() && ( file
instanceof window
.File
|| file
instanceof window
.Blob
);
148 if ( !isFileInput
&& !canUseFormData
) {
149 throw new Error( 'Unsupported argument type passed to mw.Api.upload' );
152 if ( canUseFormData
) {
153 return this.uploadWithFormData( file
, data
);
156 return this.uploadWithIframe( file
, data
);
160 * Upload a file to MediaWiki with an iframe and a form.
162 * This method is necessary for browsers without the File/FormData
163 * APIs, and continues to work in browsers with those APIs.
165 * The rough sketch of how this method works is as follows:
166 * 1. An iframe is loaded with no content.
167 * 2. A form is submitted with the passed-in file input and some extras.
168 * 3. The MediaWiki API receives that form data, and sends back a response.
169 * 4. The response is sent to the iframe, because we set target=(iframe id)
170 * 5. The response is parsed out of the iframe's document, and passed back
171 * through the promise.
174 * @param {HTMLInputElement} file The file input with a file in it.
175 * @param {Object} data Other upload options, see action=upload API docs for more
176 * @return {jQuery.Promise}
178 uploadWithIframe: function ( file
, data
) {
180 tokenPromise
= $.Deferred(),
182 deferred
= $.Deferred(),
184 id
= 'uploadframe-' + nonce
,
185 $form
= $( '<form>' ),
186 iframe
= getNewIframe( id
),
187 $iframe
= $( iframe
);
189 for ( key
in data
) {
190 if ( !fieldsAllowed
[ key
] ) {
195 data
= $.extend( {}, this.defaults
.parameters
, { action
: 'upload' }, data
);
196 $form
.addClass( 'mw-api-upload-form' );
198 $form
.css( 'display', 'none' )
200 action
: this.defaults
.ajax
.url
,
203 enctype
: 'multipart/form-data'
206 $iframe
.one( 'load', function () {
207 $iframe
.one( 'load', function () {
208 var result
= processIframeResult( iframe
);
209 deferred
.notify( 1 );
212 deferred
.reject( 'ok-but-empty', 'No response from API on upload attempt.' );
213 } else if ( result
.error
) {
214 if ( result
.error
.code
=== 'badtoken' ) {
215 api
.badToken( 'csrf' );
218 deferred
.reject( result
.error
.code
, result
);
219 } else if ( result
.upload
&& result
.upload
.warnings
) {
220 deferred
.reject( getFirstKey( result
.upload
.warnings
), result
);
222 deferred
.resolve( result
);
225 tokenPromise
.done( function () {
230 $iframe
.on( 'error', function ( error
) {
231 deferred
.reject( 'http', error
);
234 $iframe
.prop( 'src', 'about:blank' ).hide();
238 $.each( data
, function ( key
, val
) {
239 $form
.append( getHiddenInput( key
, val
) );
242 if ( !data
.filename
&& !data
.stash
) {
243 throw new Error( 'Filename not included in file data.' );
246 if ( this.needToken() ) {
247 this.getEditToken().then( function ( token
) {
248 $form
.append( getHiddenInput( 'token', token
) );
249 tokenPromise
.resolve();
250 }, tokenPromise
.reject
);
252 tokenPromise
.resolve();
255 $( 'body' ).append( $form
, $iframe
);
257 deferred
.always( function () {
262 return deferred
.promise();
266 * Uploads a file using the FormData API.
270 * @param {Object} data Other upload options, see action=upload API docs for more
271 * @return {jQuery.Promise}
273 uploadWithFormData: function ( file
, data
) {
275 deferred
= $.Deferred();
277 for ( key
in data
) {
278 if ( !fieldsAllowed
[ key
] ) {
283 data
= $.extend( {}, this.defaults
.parameters
, { action
: 'upload' }, data
);
288 if ( !data
.filename
&& !data
.stash
) {
289 throw new Error( 'Filename not included in file data.' );
292 // Use this.postWithEditToken() or this.post()
293 request
= this[ this.needToken() ? 'postWithEditToken' : 'post' ]( data
, {
294 // Use FormData (if we got here, we know that it's available)
295 contentType
: 'multipart/form-data',
296 // No timeout (default from mw.Api is 30 seconds)
298 // Provide upload progress notifications
300 var xhr
= $.ajaxSettings
.xhr();
302 // need to bind this event before we open the connection (see note at
303 // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress)
304 xhr
.upload
.addEventListener( 'progress', function ( ev
) {
305 if ( ev
.lengthComputable
) {
306 deferred
.notify( ev
.loaded
/ ev
.total
);
313 .done( function ( result
) {
314 deferred
.notify( 1 );
315 if ( result
.upload
&& result
.upload
.warnings
) {
316 deferred
.reject( getFirstKey( result
.upload
.warnings
), result
);
318 deferred
.resolve( result
);
321 .fail( function ( errorCode
, result
) {
322 deferred
.notify( 1 );
323 deferred
.reject( errorCode
, result
);
326 return deferred
.promise( { abort
: request
.abort
} );
330 * Upload a file in several chunks.
333 * @param {Object} data Other upload options, see action=upload API docs for more
334 * @param {number} [chunkSize] Size (in bytes) per chunk (default: 5MB)
335 * @param {number} [chunkRetries] Amount of times to retry a failed chunk (default: 1)
336 * @return {jQuery.Promise}
338 chunkedUpload: function ( file
, data
, chunkSize
, chunkRetries
) {
339 var start
, end
, promise
, next
, active
,
340 deferred
= $.Deferred();
342 chunkSize
= chunkSize
=== undefined ? 5 * 1024 * 1024 : chunkSize
;
343 chunkRetries
= chunkRetries
=== undefined ? 1 : chunkRetries
;
345 if ( !data
.filename
) {
346 throw new Error( 'Filename not included in file data.' );
349 // Submit first chunk to get the filekey
350 active
= promise
= this.uploadChunk( file
, data
, 0, chunkSize
, '', chunkRetries
)
351 .done( chunkSize
>= file
.size
? deferred
.resolve
: null )
352 .fail( deferred
.reject
)
353 .progress( deferred
.notify
);
355 // Now iteratively submit the rest of the chunks
356 for ( start
= chunkSize
; start
< file
.size
; start
+= chunkSize
) {
357 end
= Math
.min( start
+ chunkSize
, file
.size
);
360 // We could simply chain one this.uploadChunk after another with
361 // .then(), but then we'd hit an `Uncaught RangeError: Maximum
362 // call stack size exceeded` at as low as 1024 calls in Firefox
363 // 47. This'll work around it, but comes with the drawback of
364 // having to properly relay the results to the returned promise.
365 // eslint-disable-next-line no-loop-func
366 promise
.done( function ( start
, end
, next
, result
) {
367 var filekey
= result
.upload
.filekey
;
368 active
= this.uploadChunk( file
, data
, start
, end
, filekey
, chunkRetries
)
369 .done( end
=== file
.size
? deferred
.resolve
: next
.resolve
)
370 .fail( deferred
.reject
)
371 .progress( deferred
.notify
);
372 // start, end & next must be bound to closure, or they'd have
373 // changed by the time the promises are resolved
374 }.bind( this, start
, end
, next
) );
379 return deferred
.promise( { abort
: active
.abort
} );
387 * @param {Object} data Other upload options, see action=upload API docs for more
388 * @param {number} start Chunk start position
389 * @param {number} end Chunk end position
390 * @param {string} [filekey] File key, for follow-up chunks
391 * @param {number} [retries] Amount of times to retry request
392 * @return {jQuery.Promise}
394 uploadChunk: function ( file
, data
, start
, end
, filekey
, retries
) {
397 chunk
= this.slice( file
, start
, end
);
399 // When uploading in chunks, we're going to be issuing a lot more
400 // requests and there's always a chance of 1 getting dropped.
401 // In such case, it could be useful to try again: a network hickup
402 // doesn't necessarily have to result in upload failure...
403 retries
= retries
=== undefined ? 1 : retries
;
405 data
.filesize
= file
.size
;
409 // filekey must only be added when uploading follow-up chunks; the
410 // first chunk should never have a filekey (it'll be generated)
411 if ( filekey
&& start
!== 0 ) {
412 data
.filekey
= filekey
;
415 upload
= this.uploadWithFormData( file
, data
);
418 function ( code
, result
) {
421 // uploadWithFormData will reject uploads with warnings, but
422 // these warnings could be "harmless" or recovered from
423 // (e.g. exists-normalized, when it'll be renamed later)
424 // In the case of (only) a warning, we still want to
425 // continue the chunked upload until it completes: then
426 // reject it - at least it's been fully uploaded by then and
427 // failure handlers have a complete result object (including
428 // possibly more warnings, e.g. duplicate)
429 // This matches .upload, which also completes the upload.
430 if ( result
.upload
&& result
.upload
.warnings
&& code
in result
.upload
.warnings
) {
431 if ( end
=== file
.size
) {
432 // uploaded last chunk = reject with result data
433 return $.Deferred().reject( code
, result
);
435 // still uploading chunks = resolve to keep going
436 return $.Deferred().resolve( result
);
440 if ( retries
=== 0 ) {
441 return $.Deferred().reject( code
, result
);
444 // If the call flat out failed, we may want to try again...
445 retry
= api
.uploadChunk
.bind( this, file
, data
, start
, end
, filekey
, retries
- 1 );
446 return api
.retry( code
, result
, retry
);
448 function ( fraction
) {
449 // Since we're only uploading small parts of a file, we
450 // need to adjust the reported progress to reflect where
451 // we actually are in the combined upload
452 return ( start
+ fraction
* ( end
- start
) ) / file
.size
;
454 ).promise( { abort
: upload
.abort
} );
458 * Launch the upload anew if it failed because of network issues.
461 * @param {string} code Error code
462 * @param {Object} result API result
463 * @param {Function} callable
464 * @return {jQuery.Promise}
466 retry: function ( code
, result
, callable
) {
469 deferred
= $.Deferred(),
470 // Wrap around the callable, so that once it completes, it'll
471 // resolve/reject the promise we'll return
472 retry = function () {
473 uploadPromise
= callable();
474 uploadPromise
.then( deferred
.resolve
, deferred
.reject
);
477 // Don't retry if the request failed because we aborted it (or if
478 // it's another kind of request failure)
479 if ( code
!== 'http' || result
.textStatus
=== 'abort' ) {
480 return deferred
.reject( code
, result
);
483 retryTimer
= setTimeout( retry
, 1000 );
484 return deferred
.promise( { abort: function () {
485 // Clear the scheduled upload, or abort if already in flight
487 clearTimeout( retryTimer
);
489 if ( uploadPromise
.abort
) {
490 uploadPromise
.abort();
496 * Slice a chunk out of a File object.
500 * @param {number} start
501 * @param {number} stop
504 slice: function ( file
, start
, stop
) {
505 if ( file
.mozSlice
) {
507 return file
.mozSlice( start
, stop
, file
.type
);
508 } else if ( file
.webkitSlice
) {
510 return file
.webkitSlice( start
, stop
, file
.type
);
512 // On really old browser versions (before slice was prefixed),
513 // slice() would take (start, length) instead of (start, end)
514 // We'll ignore that here...
515 return file
.slice( start
, stop
, file
.type
);
520 * This function will handle how uploads to stash (via uploadToStash or
521 * chunkedUploadToStash) are resolved/rejected.
523 * After a successful stash, it'll resolve with a callback which, when
524 * called, will finalize the upload in stash (with the given data, or
525 * with additional/conflicting data)
527 * A failed stash can still be recovered from as long as 'filekey' is
528 * present. In that case, it'll also resolve with the callback to
529 * finalize the upload (all warnings are then ignored.)
530 * Otherwise, it'll just reject as you'd expect, with code & result.
533 * @param {jQuery.Promise} uploadPromise
534 * @param {Object} data
535 * @return {jQuery.Promise}
536 * @return {Function} return.finishUpload Call this function to finish the upload.
537 * @return {Object} return.finishUpload.data Additional data for the upload.
538 * @return {jQuery.Promise} return.finishUpload.return API promise for the final upload
539 * @return {Object} return.finishUpload.return.data API return value for the final upload
541 finishUploadToStash: function ( uploadPromise
, data
) {
545 function finishUpload( moreData
) {
546 return api
.uploadFromStash( filekey
, $.extend( data
, moreData
) );
549 return uploadPromise
.then(
550 function ( result
) {
551 filekey
= result
.upload
.filekey
;
554 function ( errorCode
, result
) {
555 if ( result
&& result
.upload
&& result
.upload
.filekey
) {
556 // Ignore any warnings if 'filekey' was returned, that's all we care about
557 filekey
= result
.upload
.filekey
;
558 return $.Deferred().resolve( finishUpload
);
560 return $.Deferred().reject( errorCode
, result
);
566 * Upload a file to the stash.
568 * This function will return a promise, which when resolved, will pass back a function
569 * to finish the stash upload. You can call that function with an argument containing
570 * more, or conflicting, data to pass to the server. For example:
572 * // upload a file to the stash with a placeholder filename
573 * api.uploadToStash( file, { filename: 'testing.png' } ).done( function ( finish ) {
574 * // finish is now the function we can use to finalize the upload
575 * // pass it a new filename from user input to override the initial value
576 * finish( { filename: getFilenameFromUser() } ).done( function ( data ) {
577 * // the upload is complete, data holds the API response
581 * @param {File|HTMLInputElement} file
582 * @param {Object} [data]
583 * @return {jQuery.Promise}
584 * @return {Function} return.finishUpload Call this function to finish the upload.
585 * @return {Object} return.finishUpload.data Additional data for the upload.
586 * @return {jQuery.Promise} return.finishUpload.return API promise for the final upload
587 * @return {Object} return.finishUpload.return.data API return value for the final upload
589 uploadToStash: function ( file
, data
) {
592 if ( !data
.filename
) {
593 throw new Error( 'Filename not included in file data.' );
596 promise
= this.upload( file
, { stash
: true, filename
: data
.filename
} );
598 return this.finishUploadToStash( promise
, data
);
602 * Upload a file to the stash, in chunks.
604 * This function will return a promise, which when resolved, will pass back a function
605 * to finish the stash upload.
607 * @see #method-uploadToStash
608 * @param {File|HTMLInputElement} file
609 * @param {Object} [data]
610 * @param {number} [chunkSize] Size (in bytes) per chunk (default: 5MB)
611 * @param {number} [chunkRetries] Amount of times to retry a failed chunk (default: 1)
612 * @return {jQuery.Promise}
613 * @return {Function} return.finishUpload Call this function to finish the upload.
614 * @return {Object} return.finishUpload.data Additional data for the upload.
615 * @return {jQuery.Promise} return.finishUpload.return API promise for the final upload
616 * @return {Object} return.finishUpload.return.data API return value for the final upload
618 chunkedUploadToStash: function ( file
, data
, chunkSize
, chunkRetries
) {
621 if ( !data
.filename
) {
622 throw new Error( 'Filename not included in file data.' );
625 promise
= this.chunkedUpload(
627 { stash
: true, filename
: data
.filename
},
632 return this.finishUploadToStash( promise
, data
);
636 * Finish an upload in the stash.
638 * @param {string} filekey
639 * @param {Object} data
640 * @return {jQuery.Promise}
642 uploadFromStash: function ( filekey
, data
) {
643 data
.filekey
= filekey
;
644 data
.action
= 'upload';
645 data
.format
= 'json';
647 if ( !data
.filename
) {
648 throw new Error( 'Filename not included in file data.' );
651 return this.postWithEditToken( data
).then( function ( result
) {
652 if ( result
.upload
&& result
.upload
.warnings
) {
653 return $.Deferred().reject( getFirstKey( result
.upload
.warnings
), result
).promise();
659 needToken: function () {
666 * @mixins mw.Api.plugin.upload
668 }( mediaWiki
, jQuery
) );