forked from therealparmesh/object-to-formdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
78 lines (62 loc) · 1.64 KB
/
index.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
'use strict'
function isUndefined (value) {
return value === undefined
}
function isObject (value) {
return value === Object(value)
}
function isArray (value) {
return Array.isArray(value)
}
function isDate (value) {
return value instanceof Date
}
function isBlob (value) {
return value &&
typeof value.size === 'number' &&
typeof value.type === 'string' &&
typeof value.slice === 'function'
}
function isFile (value) {
return isBlob(value) &&
(typeof value.lastModifiedDate === 'object' || typeof value.lastModified === 'number') &&
typeof value.name === 'string'
}
function isFormData (value) {
return value instanceof FormData
}
function objectToFormData (obj, cfg, fd, pre) {
if (isFormData(cfg)) {
pre = fd
fd = cfg
cfg = null
}
cfg = cfg || {}
cfg.indices = cfg.indices || false
fd = fd || new FormData()
if (isUndefined(obj)) {
return fd
} else if (isArray(obj)) {
obj.forEach(function (value, index) {
var key = pre + '[' + (cfg.indices ? index : '') + ']'
objectToFormData(value, cfg, fd, key)
})
} else if (isDate(obj)) {
fd.append(pre, obj.toISOString())
} else if (isObject(obj) && !isFile(obj) && !isBlob(obj)) {
Object.keys(obj).forEach(function (prop) {
var value = obj[prop]
if (isArray(value)) {
while (prop.length > 2 && prop.lastIndexOf('[]') === prop.length - 2) {
prop = prop.substring(0, prop.length - 2)
}
}
var key = pre ? (pre + '[' + prop + ']') : prop
objectToFormData(value, cfg, fd, key)
})
} else {
fd.append(pre, obj)
}
return fd
}
module.exports = objectToFormData