-
Notifications
You must be signed in to change notification settings - Fork 5
/
object-to-formdata.js
86 lines (76 loc) · 2.36 KB
/
object-to-formdata.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
object-to-formdata v0.1.2
https://github.com/nervgh/object-to-formdata
*/
(function(window) {
'use strict';
var Blob = window.Blob;
var File = window.File;
var FileList = window.FileList;
var FormData = window.FormData;
var isSupported = (Blob && File && FileList && FormData);
var toString = Object.prototype.toString;
var forEach = Array.prototype.forEach;
var map = Array.prototype.map;
if (!isSupported) return;
/**
* Returns type of anything
* @param {Object} any
* @returns {String}
*/
function getType(any) {
return toString.call(any).slice(8, -1);
}
/**
* Converts path to FormData name
* @param {Array} path
* @returns {String}
*/
function toName(path) {
var array = map.call(path, function(value) {
return '[' + value + ']';
});
array[0] = path[0];
return array.join('');
}
/**
* Converts object to FormData
* @param {Object} object
* @returns {FormData}
*/
function toFormData(object) {
var form = new FormData();
var cb = function(node, value, key, path) {
var type = getType(value);
switch (type) {
case 'Array':
break; // step into
case 'Object':
break; // step into
case 'FileList':
forEach.call(value, function(item, index) {
var way = path.concat(index);
var name = toName(way);
form.append(name, item);
});
return true; // prevent step into
case 'File':
var name = toName(path);
form.append(name, value);
return true; // prevent step into
case 'Blob':
var name = toName(path);
form.append(name, value, value.name);
return true; // prevent step into
default:
var name = toName(path);
form.append(name, value);
return true; // prevent step into
}
};
Object.traverse(object, cb, null, null, true);
return form;
}
// export
Object.toFormData = toFormData;
}(window));