2 * Provides an interface for uploading files to MediaWiki.
3 * @class mw.Api.plugin.upload
20 * Get nonce for iframe IDs on the page.
29 * Get new iframe object for an upload.
30 * @return {HTMLIframeElement}
32 function getNewIframe( id
) {
33 var frame
= document
.createElement( 'iframe' );
41 * Shortcut for getting hidden inputs
44 function getHiddenInput( name
, val
) {
45 return $( '<input type="hidden" />')
51 * Process the result of the form submission, returned to an iframe.
52 * This is the iframe's onload event.
54 * @param {HTMLIframeElement} iframe Iframe to extract result from
55 * @return {Object} Response from the server. The return value may or may
56 * not be an XMLDocument, this code was copied from elsewhere, so if you
57 * see an unexpected return type, please file a bug.
59 function processIframeResult( iframe
) {
61 doc
= iframe
.contentDocument
|| frames
[iframe
.id
].document
;
63 if ( doc
.XMLDocument
) {
64 // The response is a document property in IE
65 return doc
.XMLDocument
;
69 // Get the json string
70 // We're actually searching through an HTML doc here --
71 // according to mdale we need to do this
72 // because IE does not load JSON properly in an iframe
73 json
= $( doc
.body
).find( 'pre' ).text();
75 return JSON
.parse( json
);
78 // Response is a xml document
82 function formDataAvailable() {
83 return window
.FormData
!== undefined &&
84 window
.File
!== undefined &&
85 window
.File
.prototype.slice
!== undefined;
88 $.extend( mw
.Api
.prototype, {
90 * Upload a file to MediaWiki.
92 * The file will be uploaded using AJAX and FormData, if the browser supports it, or via an
93 * iframe if it doesn't.
95 * Caveats of iframe upload:
96 * - The returned jQuery.Promise will not receive `progress` notifications during the upload
97 * - It is incompatible with uploads to a foreign wiki using mw.ForeignApi
98 * - You must pass a HTMLInputElement and not a File for it to be possible
100 * @param {HTMLInputElement|File} file HTML input type=file element with a file already inside
101 * of it, or a File object.
102 * @param {Object} data Other upload options, see action=upload API docs for more
103 * @return {jQuery.Promise}
105 upload: function ( file
, data
) {
106 var isFileInput
, canUseFormData
;
108 isFileInput
= file
&& file
.nodeType
=== Node
.ELEMENT_NODE
;
110 if ( formDataAvailable() && isFileInput
&& file
.files
) {
111 file
= file
.files
[0];
115 return $.Deferred().reject( 'No file' );
118 canUseFormData
= formDataAvailable() && file
instanceof window
.File
;
120 if ( !isFileInput
&& !canUseFormData
) {
121 return $.Deferred().reject( 'Unsupported argument type passed to mw.Api.upload' );
124 if ( canUseFormData
) {
125 return this.uploadWithFormData( file
, data
);
128 return this.uploadWithIframe( file
, data
);
132 * Upload a file to MediaWiki with an iframe and a form.
134 * This method is necessary for browsers without the File/FormData
135 * APIs, and continues to work in browsers with those APIs.
137 * The rough sketch of how this method works is as follows:
138 * 1. An iframe is loaded with no content.
139 * 2. A form is submitted with the passed-in file input and some extras.
140 * 3. The MediaWiki API receives that form data, and sends back a response.
141 * 4. The response is sent to the iframe, because we set target=(iframe id)
142 * 5. The response is parsed out of the iframe's document, and passed back
143 * through the promise.
146 * @param {HTMLInputElement} file The file input with a file in it.
147 * @param {Object} data Other upload options, see action=upload API docs for more
148 * @return {jQuery.Promise}
150 uploadWithIframe: function ( file
, data
) {
152 tokenPromise
= $.Deferred(),
154 deferred
= $.Deferred(),
156 id
= 'uploadframe-' + nonce
,
157 $form
= $( '<form>' ),
158 iframe
= getNewIframe( id
),
159 $iframe
= $( iframe
);
161 for ( key
in data
) {
162 if ( !fieldsAllowed
[key
] ) {
167 data
= $.extend( {}, this.defaults
.parameters
, { action
: 'upload' }, data
);
168 $form
.addClass( 'mw-api-upload-form' );
170 $form
.css( 'display', 'none' )
172 action
: this.defaults
.ajax
.url
,
175 enctype
: 'multipart/form-data'
178 $iframe
.one( 'load', function () {
179 $iframe
.one( 'load', function () {
180 var result
= processIframeResult( iframe
);
183 deferred
.reject( 'No response from API on upload attempt.' );
184 } else if ( result
.error
|| result
.warnings
) {
185 if ( result
.error
&& result
.error
.code
=== 'badtoken' ) {
186 api
.badToken( 'edit' );
189 deferred
.reject( result
.error
|| result
.warnings
);
191 deferred
.notify( 1 );
192 deferred
.resolve( result
);
195 tokenPromise
.done( function () {
200 $iframe
.error( function ( error
) {
201 deferred
.reject( 'iframe failed to load: ' + error
);
204 $iframe
.prop( 'src', 'about:blank' ).hide();
208 $.each( data
, function ( key
, val
) {
209 $form
.append( getHiddenInput( key
, val
) );
212 if ( !data
.filename
&& !data
.stash
) {
213 return $.Deferred().reject( 'Filename not included in file data.' );
216 if ( this.needToken() ) {
217 this.getEditToken().then( function ( token
) {
218 $form
.append( getHiddenInput( 'token', token
) );
219 tokenPromise
.resolve();
220 }, tokenPromise
.reject
);
222 tokenPromise
.resolve();
225 $( 'body' ).append( $form
, $iframe
);
227 deferred
.always( function () {
232 return deferred
.promise();
236 * Uploads a file using the FormData API.
240 * @param {Object} data Other upload options, see action=upload API docs for more
241 * @return {jQuery.Promise}
243 uploadWithFormData: function ( file
, data
) {
245 deferred
= $.Deferred();
247 for ( key
in data
) {
248 if ( !fieldsAllowed
[key
] ) {
253 data
= $.extend( {}, this.defaults
.parameters
, { action
: 'upload' }, data
);
256 if ( !data
.filename
&& !data
.stash
) {
257 return $.Deferred().reject( 'Filename not included in file data.' );
260 // Use this.postWithEditToken() or this.post()
261 this[ this.needToken() ? 'postWithEditToken' : 'post' ]( data
, {
262 // Use FormData (if we got here, we know that it's available)
263 contentType
: 'multipart/form-data',
264 // Provide upload progress notifications
266 var xhr
= $.ajaxSettings
.xhr();
268 // need to bind this event before we open the connection (see note at
269 // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress)
270 xhr
.upload
.addEventListener( 'progress', function ( ev
) {
271 if ( ev
.lengthComputable
) {
272 deferred
.notify( ev
.loaded
/ ev
.total
);
279 .done( function ( result
) {
280 if ( result
.error
|| result
.warnings
) {
281 deferred
.reject( result
.error
|| result
.warnings
);
283 deferred
.notify( 1 );
284 deferred
.resolve( result
);
287 .fail( function ( result
) {
288 deferred
.reject( result
);
291 return deferred
.promise();
295 * Upload a file to the stash.
297 * This function will return a promise, which when resolved, will pass back a function
298 * to finish the stash upload. You can call that function with an argument containing
299 * more, or conflicting, data to pass to the server. For example:
300 * // upload a file to the stash with a placeholder filename
301 * api.uploadToStash( file, { filename: 'testing.png' } ).done( function ( finish ) {
302 * // finish is now the function we can use to finalize the upload
303 * // pass it a new filename from user input to override the initial value
304 * finish( { filename: getFilenameFromUser() } ).done( function ( data ) {
305 * // the upload is complete, data holds the API response
308 * @param {File|HTMLInputElement} file
309 * @param {Object} [data]
310 * @return {jQuery.Promise}
311 * @return {Function} return.finishStashUpload Call this function to finish the upload.
312 * @return {Object} return.finishStashUpload.data Additional data for the upload.
313 * @return {jQuery.Promise} return.finishStashUpload.return API promise for the final upload
314 * @return {Object} return.finishStashUpload.return.data API return value for the final upload
316 uploadToStash: function ( file
, data
) {
320 if ( !data
.filename
) {
321 return $.Deferred().reject( 'Filename not included in file data.' );
324 function finishUpload( moreData
) {
325 data
= $.extend( data
, moreData
);
326 data
.filekey
= filekey
;
327 data
.action
= 'upload';
328 data
.format
= 'json';
330 if ( !data
.filename
) {
331 return $.Deferred().reject( 'Filename not included in file data.' );
334 return api
.postWithEditToken( data
).then( function ( result
) {
335 if ( result
.upload
&& ( result
.upload
.error
|| result
.upload
.warnings
) ) {
336 return $.Deferred().reject( result
.upload
.error
|| result
.upload
.warnings
).promise();
342 return this.upload( file
, { stash
: true, filename
: data
.filename
} ).then( function ( result
) {
343 if ( result
&& result
.upload
&& result
.upload
.filekey
) {
344 filekey
= result
.upload
.filekey
;
345 } else if ( result
&& ( result
.error
|| result
.warning
) ) {
346 return $.Deferred().reject( result
);
353 needToken: function () {
360 * @mixins mw.Api.plugin.upload
362 }( mediaWiki
, jQuery
) );