2 * Provides an interface for uploading files to MediaWiki.
4 * @class mw.Api.plugin.upload
20 * Get nonce for iframe IDs on the page.
30 * Given a non-empty object, return one of its keys.
36 function getFirstKey( obj
) {
39 if ( obj
.hasOwnProperty( key
) ) {
46 * Get new iframe object for an upload.
49 * @return {HTMLIframeElement}
51 function getNewIframe( id
) {
52 var frame
= document
.createElement( 'iframe' );
59 * Shortcut for getting hidden inputs
64 function getHiddenInput( name
, val
) {
65 return $( '<input>' ).attr( 'type', 'hidden' )
71 * Process the result of the form submission, returned to an iframe.
72 * This is the iframe's onload event.
74 * @param {HTMLIframeElement} iframe Iframe to extract result from
75 * @return {Object} Response from the server. The return value may or may
76 * not be an XMLDocument, this code was copied from elsewhere, so if you
77 * see an unexpected return type, please file a bug.
79 function processIframeResult( iframe
) {
81 doc
= iframe
.contentDocument
|| frames
[ iframe
.id
].document
;
83 if ( doc
.XMLDocument
) {
84 // The response is a document property in IE
85 return doc
.XMLDocument
;
89 // Get the json string
90 // We're actually searching through an HTML doc here --
91 // according to mdale we need to do this
92 // because IE does not load JSON properly in an iframe
93 json
= $( doc
.body
).find( 'pre' ).text();
95 return JSON
.parse( json
);
98 // Response is a xml document
102 function formDataAvailable() {
103 return window
.FormData
!== undefined &&
104 window
.File
!== undefined &&
105 window
.File
.prototype.slice
!== undefined;
108 $.extend( mw
.Api
.prototype, {
110 * Upload a file to MediaWiki.
112 * The file will be uploaded using AJAX and FormData, if the browser supports it, or via an
113 * iframe if it doesn't.
115 * Caveats of iframe upload:
116 * - The returned jQuery.Promise will not receive `progress` notifications during the upload
117 * - It is incompatible with uploads to a foreign wiki using mw.ForeignApi
118 * - You must pass a HTMLInputElement and not a File for it to be possible
120 * @param {HTMLInputElement|File|Blob} file HTML input type=file element with a file already inside
121 * of it, or a File object.
122 * @param {Object} data Other upload options, see action=upload API docs for more
123 * @return {jQuery.Promise}
125 upload: function ( file
, data
) {
126 var isFileInput
, canUseFormData
;
128 isFileInput
= file
&& file
.nodeType
=== Node
.ELEMENT_NODE
;
130 if ( formDataAvailable() && isFileInput
&& file
.files
) {
131 file
= file
.files
[ 0 ];
135 throw new Error( 'No file' );
138 // Blobs are allowed in formdata uploads, it turns out
139 canUseFormData
= formDataAvailable() && ( file
instanceof window
.File
|| file
instanceof window
.Blob
);
141 if ( !isFileInput
&& !canUseFormData
) {
142 throw new Error( 'Unsupported argument type passed to mw.Api.upload' );
145 if ( canUseFormData
) {
146 return this.uploadWithFormData( file
, data
);
149 return this.uploadWithIframe( file
, data
);
153 * Upload a file to MediaWiki with an iframe and a form.
155 * This method is necessary for browsers without the File/FormData
156 * APIs, and continues to work in browsers with those APIs.
158 * The rough sketch of how this method works is as follows:
159 * 1. An iframe is loaded with no content.
160 * 2. A form is submitted with the passed-in file input and some extras.
161 * 3. The MediaWiki API receives that form data, and sends back a response.
162 * 4. The response is sent to the iframe, because we set target=(iframe id)
163 * 5. The response is parsed out of the iframe's document, and passed back
164 * through the promise.
167 * @param {HTMLInputElement} file The file input with a file in it.
168 * @param {Object} data Other upload options, see action=upload API docs for more
169 * @return {jQuery.Promise}
171 uploadWithIframe: function ( file
, data
) {
173 tokenPromise
= $.Deferred(),
175 deferred
= $.Deferred(),
177 id
= 'uploadframe-' + nonce
,
178 $form
= $( '<form>' ),
179 iframe
= getNewIframe( id
),
180 $iframe
= $( iframe
);
182 for ( key
in data
) {
183 if ( !fieldsAllowed
[ key
] ) {
188 data
= $.extend( {}, this.defaults
.parameters
, { action
: 'upload' }, data
);
189 $form
.addClass( 'mw-api-upload-form' );
191 $form
.css( 'display', 'none' )
193 action
: this.defaults
.ajax
.url
,
196 enctype
: 'multipart/form-data'
199 $iframe
.one( 'load', function () {
200 $iframe
.one( 'load', function () {
201 var result
= processIframeResult( iframe
);
202 deferred
.notify( 1 );
205 deferred
.reject( 'ok-but-empty', 'No response from API on upload attempt.' );
206 } else if ( result
.error
) {
207 if ( result
.error
.code
=== 'badtoken' ) {
208 api
.badToken( 'csrf' );
211 deferred
.reject( result
.error
.code
, result
);
212 } else if ( result
.upload
&& result
.upload
.warnings
) {
213 deferred
.reject( getFirstKey( result
.upload
.warnings
), result
);
215 deferred
.resolve( result
);
218 tokenPromise
.done( function () {
223 $iframe
.on( 'error', function ( error
) {
224 deferred
.reject( 'http', error
);
227 $iframe
.prop( 'src', 'about:blank' ).hide();
231 $.each( data
, function ( key
, val
) {
232 $form
.append( getHiddenInput( key
, val
) );
235 if ( !data
.filename
&& !data
.stash
) {
236 throw new Error( 'Filename not included in file data.' );
239 if ( this.needToken() ) {
240 this.getEditToken().then( function ( token
) {
241 $form
.append( getHiddenInput( 'token', token
) );
242 tokenPromise
.resolve();
243 }, tokenPromise
.reject
);
245 tokenPromise
.resolve();
248 $( 'body' ).append( $form
, $iframe
);
250 deferred
.always( function () {
255 return deferred
.promise();
259 * Uploads a file using the FormData API.
263 * @param {Object} data Other upload options, see action=upload API docs for more
264 * @return {jQuery.Promise}
266 uploadWithFormData: function ( file
, data
) {
268 deferred
= $.Deferred();
270 for ( key
in data
) {
271 if ( !fieldsAllowed
[ key
] ) {
276 data
= $.extend( {}, this.defaults
.parameters
, { action
: 'upload' }, data
);
279 if ( !data
.filename
&& !data
.stash
) {
280 throw new Error( 'Filename not included in file data.' );
283 // Use this.postWithEditToken() or this.post()
284 this[ this.needToken() ? 'postWithEditToken' : 'post' ]( data
, {
285 // Use FormData (if we got here, we know that it's available)
286 contentType
: 'multipart/form-data',
287 // No timeout (default from mw.Api is 30 seconds)
289 // Provide upload progress notifications
291 var xhr
= $.ajaxSettings
.xhr();
293 // need to bind this event before we open the connection (see note at
294 // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress)
295 xhr
.upload
.addEventListener( 'progress', function ( ev
) {
296 if ( ev
.lengthComputable
) {
297 deferred
.notify( ev
.loaded
/ ev
.total
);
304 .done( function ( result
) {
305 deferred
.notify( 1 );
306 if ( result
.upload
&& result
.upload
.warnings
) {
307 deferred
.reject( getFirstKey( result
.upload
.warnings
), result
);
309 deferred
.resolve( result
);
312 .fail( function ( errorCode
, result
) {
313 deferred
.notify( 1 );
314 deferred
.reject( errorCode
, result
);
317 return deferred
.promise();
321 * Upload a file to the stash.
323 * This function will return a promise, which when resolved, will pass back a function
324 * to finish the stash upload. You can call that function with an argument containing
325 * more, or conflicting, data to pass to the server. For example:
327 * // upload a file to the stash with a placeholder filename
328 * api.uploadToStash( file, { filename: 'testing.png' } ).done( function ( finish ) {
329 * // finish is now the function we can use to finalize the upload
330 * // pass it a new filename from user input to override the initial value
331 * finish( { filename: getFilenameFromUser() } ).done( function ( data ) {
332 * // the upload is complete, data holds the API response
336 * @param {File|HTMLInputElement} file
337 * @param {Object} [data]
338 * @return {jQuery.Promise}
339 * @return {Function} return.finishStashUpload Call this function to finish the upload.
340 * @return {Object} return.finishStashUpload.data Additional data for the upload.
341 * @return {jQuery.Promise} return.finishStashUpload.return API promise for the final upload
342 * @return {Object} return.finishStashUpload.return.data API return value for the final upload
344 uploadToStash: function ( file
, data
) {
348 if ( !data
.filename
) {
349 throw new Error( 'Filename not included in file data.' );
352 function finishUpload( moreData
) {
353 return api
.uploadFromStash( filekey
, $.extend( data
, moreData
) );
356 return this.upload( file
, { stash
: true, filename
: data
.filename
} ).then(
357 function ( result
) {
358 filekey
= result
.upload
.filekey
;
361 function ( errorCode
, result
) {
362 if ( result
&& result
.upload
&& result
.upload
.filekey
) {
363 // Ignore any warnings if 'filekey' was returned, that's all we care about
364 filekey
= result
.upload
.filekey
;
365 return $.Deferred().resolve( finishUpload
);
367 return $.Deferred().reject( errorCode
, result
);
373 * Finish an upload in the stash.
375 * @param {string} filekey
376 * @param {Object} data
378 uploadFromStash: function ( filekey
, data
) {
379 data
.filekey
= filekey
;
380 data
.action
= 'upload';
381 data
.format
= 'json';
383 if ( !data
.filename
) {
384 throw new Error( 'Filename not included in file data.' );
387 return this.postWithEditToken( data
).then( function ( result
) {
388 if ( result
.upload
&& result
.upload
.warnings
) {
389 return $.Deferred().reject( getFirstKey( result
.upload
.warnings
), result
).promise();
395 needToken: function () {
402 * @mixins mw.Api.plugin.upload
404 }( mediaWiki
, jQuery
) );