-
Notifications
You must be signed in to change notification settings - Fork 45
/
7-upload.js
43 lines (38 loc) · 1.1 KB
/
7-upload.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
//how to upload one or more files from the browser to a server
//FormData objects
//HTTP Methods POST, PATCH, PUT
let endpoint = 'http://127.0.0.1:3000/';
export function setData() {
//
const imgInput = document.getElementById('imgfile');
const jsonInput = document.getElementById('jsonfile');
document.getElementById('myform').addEventListener('submit', (ev) => {
ev.preventDefault();
//upload something
let obj = {
id: 123,
name: 'steve',
};
let jsonstring = JSON.stringify(obj);
let fd = new FormData(document.getElementById('myform'));
// console.log(imgInput.files[0]);
// fd.append('imageFile', imgInput.files[0], imgInput.files[0].name);
let request = new Request(endpoint, {
method: 'POST',
// body: jsonstring,
body: fd,
headers: {
'content-type': 'multipart/form-data',
},
});
fetch(request)
.then((response) => {
if (!response.ok) throw new Error('invalid');
return response.text();
})
.then((txt) => {
console.log(txt);
})
.catch(console.warn);
});
}