1212'use strict' ;
1313
1414type FormDataValue = any ;
15- type FormDataPart = [ string , FormDataValue ] ;
15+ type FormDataNameValuePair = [ string , FormDataValue ] ;
16+
17+ type Headers = { [ name : string ] : string } ;
18+ type FormDataPart = {
19+ string : string ;
20+ headers: Headers ;
21+ } | {
22+ uri: string ;
23+ headers: Headers ;
24+ name ? : string ;
25+ type ? : string ;
26+ } ;
1627
1728/**
1829 * Polyfill for XMLHttpRequest2 FormData API, allowing multipart POST requests
1930 * with mixed data (string, native files) to be submitted via XMLHttpRequest.
31+ *
32+ * Example:
33+ *
34+ * var photo = {
35+ * uri: uriFromCameraRoll,
36+ * type: 'image/jpeg',
37+ * name: 'photo.jpg',
38+ * };
39+ *
40+ * var body = new FormData();
41+ * body.append('authToken', 'secret');
42+ * body.append('photo', photo);
43+ * body.append('title', 'A beautiful photo!');
44+ *
45+ * xhr.open('POST', serverURL);
46+ * xhr.send(body);
2047 */
2148class FormData {
22- _parts : Array < FormDataPart > ;
23- _partsByKey: { [ key : string ] : FormDataPart } ;
49+ _parts : Array < FormDataNameValuePair > ;
50+ _partsByKey: { [ key : string ] : FormDataNameValuePair } ;
2451
2552 constructor() {
2653 this . _parts = [ ] ;
@@ -42,24 +69,25 @@ class FormData {
4269 this . _partsByKey [ key ] = parts ;
4370 }
4471
45- getParts ( ) : Array < FormDataValue > {
72+ getParts ( ) : Array < FormDataPart > {
4673 return this . _parts . map ( ( [ name , value ] ) => {
74+ var contentDisposition = 'form-data; name="' + name + '"' ;
75+ var headers : Headers = { 'content-disposition' : contentDisposition } ;
4776 if ( typeof value === 'string' ) {
48- return {
49- string : value ,
50- headers : {
51- 'content-disposition' : 'form-data; name="' + name + '"' ,
52- } ,
53- } ;
77+ return { string : value , headers} ;
5478 }
55- var contentDisposition = 'form-data; name="' + name + '"' ;
79+
80+ // The body part is a "blob", which in React Native just means
81+ // an object with a `uri` attribute. Optionally, it can also
82+ // have a `name` and `type` attribute to specify filename and
83+ // content type (cf. web Blob interface.)
5684 if ( typeof value . name === 'string' ) {
57- contentDisposition += '; filename="' + value . name + '"' ;
85+ headers [ 'content-disposition' ] += '; filename="' + value . name + '"' ;
86+ }
87+ if ( typeof value . type === 'string' ) {
88+ headers [ 'content-type' ] = value . type ;
5889 }
59- return {
60- ...value ,
61- headers : { 'content-disposition' : contentDisposition } ,
62- } ;
90+ return { ...value , headers} ;
6391 } ) ;
6492 }
6593}
0 commit comments