-
Notifications
You must be signed in to change notification settings - Fork 0
/
FormData.js
68 lines (64 loc) · 2.14 KB
/
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
/**
* FormData class creates a form data object to be used for sending data in a multipart/form-data format.
*
* @class FormData
*
* @constructor
* Initializes the boundary and payload properties. The boundary is a string that separates the different parts of the form data.
*
* @method append
* Adds a new field with the given name and value to the form data. If the value is a Blob object, the field is treated as a file and its content type is set accordingly.
*
* @method getBoundary
* Returns the boundary string.
*
* @method getPayload
* Returns the payload of the form data.
*/
class FormData {
constructor() {
this.boundary = "---------------------------" + Date.now().toString(16);
this.payload = [];
}
/**
* Returns the boundary string.
*
* @method getBoundary
*
* @return {string} boundary
*/
getBoundary() { return this.boundary; }
/**
* Returns the payload of the form data.
*
* @method getPayload
*
* @return {Array} payload
*/
getPayload() { return this.payload }
/**
* Adds a new field with the given name and value to the form data.
* If the value is a Blob object, the field is treated as a file and its content type is set accordingly.
*
* @method append
*
* @param {string} name - The name of the field.
* @param {(string|Blob)} value - The value of the field. Can be a string or a Blob object.
*/
append(name, value) {
try {
const data = "--" + this.getBoundary() + "\r\n" +
"Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + value.getName() + "\"\r\n" +
"Content-Type:" + value.getMimeType() + "\r\n\r\n";
this.payload = this.payload.concat(Utilities.newBlob(data).getBytes())
.concat(value.getBlob().getBytes())
.concat(Utilities.newBlob("\r\n--" + this.getBoundary() + "--").getBytes());
} catch (err) {
const data = "--" + this.getBoundary() + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; \r\n\r\n" + value + "\r\n";
this.payload = this.payload.concat(Utilities.newBlob(data).getBytes())
}
}
}
function newFormData() {
return new FormData()
}