9814142a21ad04371731b7cd30f6f31782731496
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 .fail( deferred
.reject
)
352 .progress( deferred
.notify
);
354 // Now iteratively submit the rest of the chunks
355 for ( start
= chunkSize
; start
< file
.size
; start
+= chunkSize
) {
356 end
= Math
.min( start
+ chunkSize
, file
.size
);
359 // We could simply chain one this.uploadChunk after another with
360 // .then(), but then we'd hit an `Uncaught RangeError: Maximum
361 // call stack size exceeded` at as low as 1024 calls in Firefox
362 // 47. This'll work around it, but comes with the drawback of
363 // having to properly relay the results to the returned promise.
364 // eslint-disable-next-line no-loop-func
365 promise
.done( function ( start
, end
, next
, result
) {
366 var filekey
= result
.upload
.filekey
;
367 active
= this.uploadChunk( file
, data
, start
, end
, filekey
, chunkRetries
)
368 .done( end
=== file
.size
? deferred
.resolve
: next
.resolve
)
369 .fail( deferred
.reject
)
370 .progress( deferred
.notify
);
371 // start, end & next must be bound to closure, or they'd have
372 // changed by the time the promises are resolved
373 }.bind( this, start
, end
, next
) );
378 return deferred
.promise( { abort
: active
.abort
} );
386 * @param {Object} data Other upload options, see action=upload API docs for more
387 * @param {number} start Chunk start position
388 * @param {number} end Chunk end position
389 * @param {string} [filekey] File key, for follow-up chunks
390 * @param {number} [retries] Amount of times to retry request
391 * @return {jQuery.Promise}
393 uploadChunk: function ( file
, data
, start
, end
, filekey
, retries
) {
396 chunk
= this.slice( file
, start
, end
);
398 // When uploading in chunks, we're going to be issuing a lot more
399 // requests and there's always a chance of 1 getting dropped.
400 // In such case, it could be useful to try again: a network hickup
401 // doesn't necessarily have to result in upload failure...
402 retries
= retries
=== undefined ? 1 : retries
;
403 retry = function ( code
, result
) {
404 var deferred
= $.Deferred(),
405 callback = function () {
406 api
.uploadChunk( file
, data
, start
, end
, filekey
, retries
- 1 )
407 .then( deferred
.resolve
, deferred
.reject
);
410 // Don't retry if the request failed because we aborted it (or
411 // if it's another kind of request failure)
412 if ( code
!== 'http' || result
.textStatus
=== 'abort' ) {
413 return deferred
.reject( code
, result
);
416 setTimeout( callback
, 1000 );
417 return deferred
.promise();
420 data
.filesize
= file
.size
;
424 // filekey must only be added when uploading follow-up chunks; the
425 // first chunk should never have a filekey (it'll be generated)
426 if ( filekey
&& start
!== 0 ) {
427 data
.filekey
= filekey
;
430 upload
= this.uploadWithFormData( file
, data
);
433 // If the call fails, we may want to try again...
434 retries
=== 0 ? null : retry
,
435 function ( fraction
) {
436 // Since we're only uploading small parts of a file, we
437 // need to adjust the reported progress to reflect where
438 // we actually are in the combined upload
439 return ( start
+ fraction
* ( end
- start
) ) / file
.size
;
441 ).promise( { abort
: upload
.abort
} );
445 * Slice a chunk out of a File object.
449 * @param {number} start
450 * @param {number} stop
453 slice: function ( file
, start
, stop
) {
454 if ( file
.mozSlice
) {
456 return file
.mozSlice( start
, stop
, file
.type
);
457 } else if ( file
.webkitSlice
) {
459 return file
.webkitSlice( start
, stop
, file
.type
);
461 // On really old browser versions (before slice was prefixed),
462 // slice() would take (start, length) instead of (start, end)
463 // We'll ignore that here...
464 return file
.slice( start
, stop
, file
.type
);
469 * This function will handle how uploads to stash (via uploadToStash or
470 * chunkedUploadToStash) are resolved/rejected.
472 * After a successful stash, it'll resolve with a callback which, when
473 * called, will finalize the upload in stash (with the given data, or
474 * with additional/conflicting data)
476 * A failed stash can still be recovered from as long as 'filekey' is
477 * present. In that case, it'll also resolve with the callback to
478 * finalize the upload (all warnings are then ignored.)
479 * Otherwise, it'll just reject as you'd expect, with code & result.
482 * @param {jQuery.Promise} uploadPromise
483 * @param {Object} data
484 * @return {jQuery.Promise}
485 * @return {Function} return.finishUpload Call this function to finish the upload.
486 * @return {Object} return.finishUpload.data Additional data for the upload.
487 * @return {jQuery.Promise} return.finishUpload.return API promise for the final upload
488 * @return {Object} return.finishUpload.return.data API return value for the final upload
490 finishUploadToStash: function ( uploadPromise
, data
) {
494 function finishUpload( moreData
) {
495 return api
.uploadFromStash( filekey
, $.extend( data
, moreData
) );
498 return uploadPromise
.then(
499 function ( result
) {
500 filekey
= result
.upload
.filekey
;
503 function ( errorCode
, result
) {
504 if ( result
&& result
.upload
&& result
.upload
.filekey
) {
505 // Ignore any warnings if 'filekey' was returned, that's all we care about
506 filekey
= result
.upload
.filekey
;
507 return $.Deferred().resolve( finishUpload
);
509 return $.Deferred().reject( errorCode
, result
);
515 * Upload a file to the stash.
517 * This function will return a promise, which when resolved, will pass back a function
518 * to finish the stash upload. You can call that function with an argument containing
519 * more, or conflicting, data to pass to the server. For example:
521 * // upload a file to the stash with a placeholder filename
522 * api.uploadToStash( file, { filename: 'testing.png' } ).done( function ( finish ) {
523 * // finish is now the function we can use to finalize the upload
524 * // pass it a new filename from user input to override the initial value
525 * finish( { filename: getFilenameFromUser() } ).done( function ( data ) {
526 * // the upload is complete, data holds the API response
530 * @param {File|HTMLInputElement} file
531 * @param {Object} [data]
532 * @return {jQuery.Promise}
533 * @return {Function} return.finishUpload Call this function to finish the upload.
534 * @return {Object} return.finishUpload.data Additional data for the upload.
535 * @return {jQuery.Promise} return.finishUpload.return API promise for the final upload
536 * @return {Object} return.finishUpload.return.data API return value for the final upload
538 uploadToStash: function ( file
, data
) {
541 if ( !data
.filename
) {
542 throw new Error( 'Filename not included in file data.' );
545 promise
= this.upload( file
, { stash
: true, filename
: data
.filename
} );
547 return this.finishUploadToStash( promise
, data
);
551 * Upload a file to the stash, in chunks.
553 * This function will return a promise, which when resolved, will pass back a function
554 * to finish the stash upload.
556 * @see #method-uploadToStash
557 * @param {File|HTMLInputElement} file
558 * @param {Object} [data]
559 * @param {number} [chunkSize] Size (in bytes) per chunk (default: 5MB)
560 * @param {number} [chunkRetries] Amount of times to retry a failed chunk (default: 1)
561 * @return {jQuery.Promise}
562 * @return {Function} return.finishUpload Call this function to finish the upload.
563 * @return {Object} return.finishUpload.data Additional data for the upload.
564 * @return {jQuery.Promise} return.finishUpload.return API promise for the final upload
565 * @return {Object} return.finishUpload.return.data API return value for the final upload
567 chunkedUploadToStash: function ( file
, data
, chunkSize
, chunkRetries
) {
570 if ( !data
.filename
) {
571 throw new Error( 'Filename not included in file data.' );
574 promise
= this.chunkedUpload(
576 { stash
: true, filename
: data
.filename
},
581 return this.finishUploadToStash( promise
, data
);
585 * Finish an upload in the stash.
587 * @param {string} filekey
588 * @param {Object} data
589 * @return {jQuery.Promise}
591 uploadFromStash: function ( filekey
, data
) {
592 data
.filekey
= filekey
;
593 data
.action
= 'upload';
594 data
.format
= 'json';
596 if ( !data
.filename
) {
597 throw new Error( 'Filename not included in file data.' );
600 return this.postWithEditToken( data
).then( function ( result
) {
601 if ( result
.upload
&& result
.upload
.warnings
) {
602 return $.Deferred().reject( getFirstKey( result
.upload
.warnings
), result
).promise();
608 needToken: function () {
615 * @mixins mw.Api.plugin.upload
617 }( mediaWiki
, jQuery
) );