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
) {
48 * Get new iframe object for an upload.
52 * @return {HTMLIframeElement}
54 function getNewIframe( id
) {
55 var frame
= document
.createElement( 'iframe' );
62 * Shortcut for getting hidden inputs
65 * @param {string} name
69 function getHiddenInput( name
, val
) {
70 return $( '<input>' ).attr( 'type', 'hidden' )
76 * Process the result of the form submission, returned to an iframe.
77 * This is the iframe's onload event.
79 * @param {HTMLIframeElement} iframe Iframe to extract result from
80 * @return {Object} Response from the server. The return value may or may
81 * not be an XMLDocument, this code was copied from elsewhere, so if you
82 * see an unexpected return type, please file a bug.
84 function processIframeResult( iframe
) {
86 doc
= iframe
.contentDocument
|| frames
[ iframe
.id
].document
;
88 if ( doc
.XMLDocument
) {
89 // The response is a document property in IE
90 return doc
.XMLDocument
;
94 // Get the json string
95 // We're actually searching through an HTML doc here --
96 // according to mdale we need to do this
97 // because IE does not load JSON properly in an iframe
98 json
= $( doc
.body
).find( 'pre' ).text();
100 return JSON
.parse( json
);
103 // Response is a xml document
107 function formDataAvailable() {
108 return window
.FormData
!== undefined &&
109 window
.File
!== undefined &&
110 window
.File
.prototype.slice
!== undefined;
113 $.extend( mw
.Api
.prototype, {
115 * Upload a file to MediaWiki.
117 * The file will be uploaded using AJAX and FormData, if the browser supports it, or via an
118 * iframe if it doesn't.
120 * Caveats of iframe upload:
121 * - The returned jQuery.Promise will not receive `progress` notifications during the upload
122 * - It is incompatible with uploads to a foreign wiki using mw.ForeignApi
123 * - You must pass a HTMLInputElement and not a File for it to be possible
125 * @param {HTMLInputElement|File|Blob} file HTML input type=file element with a file already inside
126 * of it, or a File object.
127 * @param {Object} data Other upload options, see action=upload API docs for more
128 * @return {jQuery.Promise}
130 upload: function ( file
, data
) {
131 var isFileInput
, canUseFormData
;
133 isFileInput
= file
&& file
.nodeType
=== Node
.ELEMENT_NODE
;
135 if ( formDataAvailable() && isFileInput
&& file
.files
) {
136 file
= file
.files
[ 0 ];
140 throw new Error( 'No file' );
143 // Blobs are allowed in formdata uploads, it turns out
144 canUseFormData
= formDataAvailable() && ( file
instanceof window
.File
|| file
instanceof window
.Blob
);
146 if ( !isFileInput
&& !canUseFormData
) {
147 throw new Error( 'Unsupported argument type passed to mw.Api.upload' );
150 if ( canUseFormData
) {
151 return this.uploadWithFormData( file
, data
);
154 return this.uploadWithIframe( file
, data
);
158 * Upload a file to MediaWiki with an iframe and a form.
160 * This method is necessary for browsers without the File/FormData
161 * APIs, and continues to work in browsers with those APIs.
163 * The rough sketch of how this method works is as follows:
164 * 1. An iframe is loaded with no content.
165 * 2. A form is submitted with the passed-in file input and some extras.
166 * 3. The MediaWiki API receives that form data, and sends back a response.
167 * 4. The response is sent to the iframe, because we set target=(iframe id)
168 * 5. The response is parsed out of the iframe's document, and passed back
169 * through the promise.
172 * @param {HTMLInputElement} file The file input with a file in it.
173 * @param {Object} data Other upload options, see action=upload API docs for more
174 * @return {jQuery.Promise}
176 uploadWithIframe: function ( file
, data
) {
178 tokenPromise
= $.Deferred(),
180 deferred
= $.Deferred(),
182 id
= 'uploadframe-' + nonce
,
183 $form
= $( '<form>' ),
184 iframe
= getNewIframe( id
),
185 $iframe
= $( iframe
);
187 for ( key
in data
) {
188 if ( !fieldsAllowed
[ key
] ) {
193 data
= $.extend( {}, this.defaults
.parameters
, { action
: 'upload' }, data
);
194 $form
.addClass( 'mw-api-upload-form' );
196 $form
.css( 'display', 'none' )
198 action
: this.defaults
.ajax
.url
,
201 enctype
: 'multipart/form-data'
204 $iframe
.one( 'load', function () {
205 $iframe
.one( 'load', function () {
206 var result
= processIframeResult( iframe
);
207 deferred
.notify( 1 );
210 deferred
.reject( 'ok-but-empty', 'No response from API on upload attempt.' );
211 } else if ( result
.error
) {
212 if ( result
.error
.code
=== 'badtoken' ) {
213 api
.badToken( 'csrf' );
216 deferred
.reject( result
.error
.code
, result
);
217 } else if ( result
.upload
&& result
.upload
.warnings
) {
218 deferred
.reject( getFirstKey( result
.upload
.warnings
), result
);
220 deferred
.resolve( result
);
223 tokenPromise
.done( function () {
228 $iframe
.on( 'error', function ( error
) {
229 deferred
.reject( 'http', error
);
232 $iframe
.prop( 'src', 'about:blank' ).hide();
236 $.each( data
, function ( key
, val
) {
237 $form
.append( getHiddenInput( key
, val
) );
240 if ( !data
.filename
&& !data
.stash
) {
241 throw new Error( 'Filename not included in file data.' );
244 if ( this.needToken() ) {
245 this.getEditToken().then( function ( token
) {
246 $form
.append( getHiddenInput( 'token', token
) );
247 tokenPromise
.resolve();
248 }, tokenPromise
.reject
);
250 tokenPromise
.resolve();
253 $( 'body' ).append( $form
, $iframe
);
255 deferred
.always( function () {
260 return deferred
.promise();
264 * Uploads a file using the FormData API.
268 * @param {Object} data Other upload options, see action=upload API docs for more
269 * @return {jQuery.Promise}
271 uploadWithFormData: function ( file
, data
) {
273 deferred
= $.Deferred();
275 for ( key
in data
) {
276 if ( !fieldsAllowed
[ key
] ) {
281 data
= $.extend( {}, this.defaults
.parameters
, { action
: 'upload' }, data
);
286 if ( !data
.filename
&& !data
.stash
) {
287 throw new Error( 'Filename not included in file data.' );
290 // Use this.postWithEditToken() or this.post()
291 request
= this[ this.needToken() ? 'postWithEditToken' : 'post' ]( data
, {
292 // Use FormData (if we got here, we know that it's available)
293 contentType
: 'multipart/form-data',
294 // No timeout (default from mw.Api is 30 seconds)
296 // Provide upload progress notifications
298 var xhr
= $.ajaxSettings
.xhr();
300 // need to bind this event before we open the connection (see note at
301 // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress)
302 xhr
.upload
.addEventListener( 'progress', function ( ev
) {
303 if ( ev
.lengthComputable
) {
304 deferred
.notify( ev
.loaded
/ ev
.total
);
311 .done( function ( result
) {
312 deferred
.notify( 1 );
313 if ( result
.upload
&& result
.upload
.warnings
) {
314 deferred
.reject( getFirstKey( result
.upload
.warnings
), result
);
316 deferred
.resolve( result
);
319 .fail( function ( errorCode
, result
) {
320 deferred
.notify( 1 );
321 deferred
.reject( errorCode
, result
);
324 return deferred
.promise( { abort
: request
.abort
} );
328 * Upload a file in several chunks.
331 * @param {Object} data Other upload options, see action=upload API docs for more
332 * @param {number} [chunkSize] Size (in bytes) per chunk (default: 5MB)
333 * @param {number} [chunkRetries] Amount of times to retry a failed chunk (default: 1)
334 * @return {jQuery.Promise}
336 chunkedUpload: function ( file
, data
, chunkSize
, chunkRetries
) {
337 var start
, end
, promise
, next
, active
,
338 deferred
= $.Deferred();
340 chunkSize
= chunkSize
=== undefined ? 5 * 1024 * 1024 : chunkSize
;
341 chunkRetries
= chunkRetries
=== undefined ? 1 : chunkRetries
;
343 if ( !data
.filename
) {
344 throw new Error( 'Filename not included in file data.' );
347 // Submit first chunk to get the filekey
348 active
= promise
= this.uploadChunk( file
, data
, 0, chunkSize
, '', chunkRetries
)
349 .done( chunkSize
>= file
.size
? deferred
.resolve
: null )
350 .fail( deferred
.reject
)
351 .progress( deferred
.notify
);
353 // Now iteratively submit the rest of the chunks
354 for ( start
= chunkSize
; start
< file
.size
; start
+= chunkSize
) {
355 end
= Math
.min( start
+ chunkSize
, file
.size
);
358 // We could simply chain one this.uploadChunk after another with
359 // .then(), but then we'd hit an `Uncaught RangeError: Maximum
360 // call stack size exceeded` at as low as 1024 calls in Firefox
361 // 47. This'll work around it, but comes with the drawback of
362 // having to properly relay the results to the returned promise.
363 // eslint-disable-next-line no-loop-func
364 promise
.done( function ( start
, end
, next
, result
) {
365 var filekey
= result
.upload
.filekey
;
366 active
= this.uploadChunk( file
, data
, start
, end
, filekey
, chunkRetries
)
367 .done( end
=== file
.size
? deferred
.resolve
: next
.resolve
)
368 .fail( deferred
.reject
)
369 .progress( deferred
.notify
);
370 // start, end & next must be bound to closure, or they'd have
371 // changed by the time the promises are resolved
372 }.bind( this, start
, end
, next
) );
377 return deferred
.promise( { abort
: active
.abort
} );
385 * @param {Object} data Other upload options, see action=upload API docs for more
386 * @param {number} start Chunk start position
387 * @param {number} end Chunk end position
388 * @param {string} [filekey] File key, for follow-up chunks
389 * @param {number} [retries] Amount of times to retry request
390 * @return {jQuery.Promise}
392 uploadChunk: function ( file
, data
, start
, end
, filekey
, retries
) {
395 chunk
= this.slice( file
, start
, end
);
397 // When uploading in chunks, we're going to be issuing a lot more
398 // requests and there's always a chance of 1 getting dropped.
399 // In such case, it could be useful to try again: a network hickup
400 // doesn't necessarily have to result in upload failure...
401 retries
= retries
=== undefined ? 1 : retries
;
403 data
.filesize
= file
.size
;
407 // filekey must only be added when uploading follow-up chunks; the
408 // first chunk should never have a filekey (it'll be generated)
409 if ( filekey
&& start
!== 0 ) {
410 data
.filekey
= filekey
;
413 upload
= this.uploadWithFormData( file
, data
);
416 function ( code
, result
) {
419 // uploadWithFormData will reject uploads with warnings, but
420 // these warnings could be "harmless" or recovered from
421 // (e.g. exists-normalized, when it'll be renamed later)
422 // In the case of (only) a warning, we still want to
423 // continue the chunked upload until it completes: then
424 // reject it - at least it's been fully uploaded by then and
425 // failure handlers have a complete result object (including
426 // possibly more warnings, e.g. duplicate)
427 // This matches .upload, which also completes the upload.
428 if ( result
.upload
&& result
.upload
.warnings
&& code
in result
.upload
.warnings
) {
429 if ( end
=== file
.size
) {
430 // uploaded last chunk = reject with result data
431 return $.Deferred().reject( code
, result
);
433 // still uploading chunks = resolve to keep going
434 return $.Deferred().resolve( result
);
438 if ( retries
=== 0 ) {
439 return $.Deferred().reject( code
, result
);
442 // If the call flat out failed, we may want to try again...
443 retry
= api
.uploadChunk
.bind( this, file
, data
, start
, end
, filekey
, retries
- 1 );
444 return api
.retry( code
, result
, retry
);
446 function ( fraction
) {
447 // Since we're only uploading small parts of a file, we
448 // need to adjust the reported progress to reflect where
449 // we actually are in the combined upload
450 return ( start
+ fraction
* ( end
- start
) ) / file
.size
;
452 ).promise( { abort
: upload
.abort
} );
456 * Launch the upload anew if it failed because of network issues.
459 * @param {string} code Error code
460 * @param {Object} result API result
461 * @param {Function} callable
462 * @return {jQuery.Promise}
464 retry: function ( code
, result
, callable
) {
467 deferred
= $.Deferred(),
468 // Wrap around the callable, so that once it completes, it'll
469 // resolve/reject the promise we'll return
470 retry = function () {
471 uploadPromise
= callable();
472 uploadPromise
.then( deferred
.resolve
, deferred
.reject
);
475 // Don't retry if the request failed because we aborted it (or if
476 // it's another kind of request failure)
477 if ( code
!== 'http' || result
.textStatus
=== 'abort' ) {
478 return deferred
.reject( code
, result
);
481 retryTimer
= setTimeout( retry
, 1000 );
482 return deferred
.promise( { abort: function () {
483 // Clear the scheduled upload, or abort if already in flight
485 clearTimeout( retryTimer
);
487 if ( uploadPromise
.abort
) {
488 uploadPromise
.abort();
494 * Slice a chunk out of a File object.
498 * @param {number} start
499 * @param {number} stop
502 slice: function ( file
, start
, stop
) {
503 if ( file
.mozSlice
) {
505 return file
.mozSlice( start
, stop
, file
.type
);
506 } else if ( file
.webkitSlice
) {
508 return file
.webkitSlice( start
, stop
, file
.type
);
510 // On really old browser versions (before slice was prefixed),
511 // slice() would take (start, length) instead of (start, end)
512 // We'll ignore that here...
513 return file
.slice( start
, stop
, file
.type
);
518 * This function will handle how uploads to stash (via uploadToStash or
519 * chunkedUploadToStash) are resolved/rejected.
521 * After a successful stash, it'll resolve with a callback which, when
522 * called, will finalize the upload in stash (with the given data, or
523 * with additional/conflicting data)
525 * A failed stash can still be recovered from as long as 'filekey' is
526 * present. In that case, it'll also resolve with the callback to
527 * finalize the upload (all warnings are then ignored.)
528 * Otherwise, it'll just reject as you'd expect, with code & result.
531 * @param {jQuery.Promise} uploadPromise
532 * @param {Object} data
533 * @return {jQuery.Promise}
534 * @return {Function} return.finishUpload Call this function to finish the upload.
535 * @return {Object} return.finishUpload.data Additional data for the upload.
536 * @return {jQuery.Promise} return.finishUpload.return API promise for the final upload
537 * @return {Object} return.finishUpload.return.data API return value for the final upload
539 finishUploadToStash: function ( uploadPromise
, data
) {
543 function finishUpload( moreData
) {
544 return api
.uploadFromStash( filekey
, $.extend( data
, moreData
) );
547 return uploadPromise
.then(
548 function ( result
) {
549 filekey
= result
.upload
.filekey
;
552 function ( errorCode
, result
) {
553 if ( result
&& result
.upload
&& result
.upload
.filekey
) {
554 // Ignore any warnings if 'filekey' was returned, that's all we care about
555 filekey
= result
.upload
.filekey
;
556 return $.Deferred().resolve( finishUpload
);
558 return $.Deferred().reject( errorCode
, result
);
564 * Upload a file to the stash.
566 * This function will return a promise, which when resolved, will pass back a function
567 * to finish the stash upload. You can call that function with an argument containing
568 * more, or conflicting, data to pass to the server. For example:
570 * // upload a file to the stash with a placeholder filename
571 * api.uploadToStash( file, { filename: 'testing.png' } ).done( function ( finish ) {
572 * // finish is now the function we can use to finalize the upload
573 * // pass it a new filename from user input to override the initial value
574 * finish( { filename: getFilenameFromUser() } ).done( function ( data ) {
575 * // the upload is complete, data holds the API response
579 * @param {File|HTMLInputElement} file
580 * @param {Object} [data]
581 * @return {jQuery.Promise}
582 * @return {Function} return.finishUpload Call this function to finish the upload.
583 * @return {Object} return.finishUpload.data Additional data for the upload.
584 * @return {jQuery.Promise} return.finishUpload.return API promise for the final upload
585 * @return {Object} return.finishUpload.return.data API return value for the final upload
587 uploadToStash: function ( file
, data
) {
590 if ( !data
.filename
) {
591 throw new Error( 'Filename not included in file data.' );
594 promise
= this.upload( file
, { stash
: true, filename
: data
.filename
} );
596 return this.finishUploadToStash( promise
, data
);
600 * Upload a file to the stash, in chunks.
602 * This function will return a promise, which when resolved, will pass back a function
603 * to finish the stash upload.
605 * @see #method-uploadToStash
606 * @param {File|HTMLInputElement} file
607 * @param {Object} [data]
608 * @param {number} [chunkSize] Size (in bytes) per chunk (default: 5MB)
609 * @param {number} [chunkRetries] Amount of times to retry a failed chunk (default: 1)
610 * @return {jQuery.Promise}
611 * @return {Function} return.finishUpload Call this function to finish the upload.
612 * @return {Object} return.finishUpload.data Additional data for the upload.
613 * @return {jQuery.Promise} return.finishUpload.return API promise for the final upload
614 * @return {Object} return.finishUpload.return.data API return value for the final upload
616 chunkedUploadToStash: function ( file
, data
, chunkSize
, chunkRetries
) {
619 if ( !data
.filename
) {
620 throw new Error( 'Filename not included in file data.' );
623 promise
= this.chunkedUpload(
625 { stash
: true, filename
: data
.filename
},
630 return this.finishUploadToStash( promise
, data
);
634 * Finish an upload in the stash.
636 * @param {string} filekey
637 * @param {Object} data
638 * @return {jQuery.Promise}
640 uploadFromStash: function ( filekey
, data
) {
641 data
.filekey
= filekey
;
642 data
.action
= 'upload';
643 data
.format
= 'json';
645 if ( !data
.filename
) {
646 throw new Error( 'Filename not included in file data.' );
649 return this.postWithEditToken( data
).then( function ( result
) {
650 if ( result
.upload
&& result
.upload
.warnings
) {
651 return $.Deferred().reject( getFirstKey( result
.upload
.warnings
), result
).promise();
657 needToken: function () {
664 * @mixins mw.Api.plugin.upload
666 }( mediaWiki
, jQuery
) );