Created
July 21, 2017 01:47
-
-
Save chungchi300/d7af9e1f668a4752f6f1f096e5307a21 to your computer and use it in GitHub Desktop.
Fetch file upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //very important,these javascript component is more debuggable then native | |
| import fetch from 'isomorphic-fetch'; | |
| import FormData from 'form-data'; | |
| let formData = new FormData(); | |
| formData.append('file',fs.createReadStream('test/api/testMedia.jpg')); | |
| //implement your own header function | |
| let headers = prepareHeaders(); | |
| // !! must ,delete header content type is header is neccessary , the fetch will help you decide the content type is multipart/form-data and add suitable boundary because your body contains file object. | |
| if (headers['Content-Type'] == 'multipart/form-data') { | |
| delete headers['Content-Type']; | |
| delete headers['content-type']; | |
| } | |
| let opts = { | |
| method: 'POST', | |
| credentials: 'include', | |
| headers: headers, | |
| body: formData, | |
| }; | |
| fetch('domain.com/api/snapshot/create', opts); | |
| //the header actually will be multipart/form-data; boundary=----WebKitFormBoundaryp9etszBwQn98OTCR | |
| /** the body will like | |
| ------WebKitFormBoundaryp9etszBwQn98OTCR | |
| Content-Disposition: form-data; name="qquuid" | |
| 5fb1384e-1a88-41e7-b50c-c6498b7f49cb | |
| ------WebKitFormBoundaryp9etszBwQn98OTCR | |
| Content-Disposition: form-data; name="qqfilename" | |
| download.png | |
| ------WebKitFormBoundaryp9etszBwQn98OTCR | |
| Content-Disposition: form-data; name="qqtotalfilesize" | |
| 2014 | |
| ------WebKitFormBoundaryp9etszBwQn98OTCR | |
| Content-Disposition: form-data; name="file"; filename="download.png" | |
| Content-Type: image/png | |
| ------WebKitFormBoundaryp9etszBwQn98OTCR-- | |
| **/ | |
Author
Hello,
I am doing similar process, I add authorization header and delete (C/c)ontent-type header but when I use fetch the header don't have any content type or boundary so the request fail.
Do you have any advices ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Remember request/response writer always decide the content first then the header