ded / reqwest

browser asynchronous http requests
2.94k stars 343 forks source link

Unable to send multipart/form-data request #264

Open manishchauhanquovantis opened 7 years ago

manishchauhanquovantis commented 7 years ago

Hey, I need to upload multiple files to my node.js server but when i run reqwest({ url: url, method: "POST", contentType: "multipart/form-data", data: data, headers: headers }).

It fails to send files to my nodejs API. Node.JS API `router.post('/upload', upload.fields([ { name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 } ]), function(req, res, next) { res.status(200); res.send('Successfully uploaded ' + req.files.length + ' files!') })

I even tried specifying boundry but that even didn't worked

But when i tried with jquery it worked ` var form = new FormData(); form.append("avatar", "roku project (1).docx"); form.append("asdasd", "asdasd"); form.append("asdasd", "asdasd");

var settings = { "async": true, "crossDomain": true, "url": "http://localhost:3000/v1/users/upload", "method": "POST", "headers": { "cache-control": "no-cache", "postman-token": "78a9f343-6b45-82ba-4850-57b6beeed937" }, "processData": false, "contentType": false, "mimeType": "multipart/form-data", "data": form }

$.ajax(settings).done(function (response) { console.log(response); }); `

blizzardengle commented 7 years ago

This should me marked as closed. Jquery's Ajax will work because it handles sending files for you. It will start with the latest API's like FormData and work all the way down to submitting the form in an iFrame.

Reqwest and any other Ajax function or API that relies on the traditional XMLHttpRequest can not submit forms that include files. When using ajax (or XMLHttpRequest really) you are responsible for preparing the forms data to send, usually using a serialize function, but you can not do that to a file; meaning you can not serialize a file for sending like you can with other inputs.

What you'll have to do is add a check to your code to see if the form attempting to be submitted has a file input in it. If so you must not try to send it with reqwest but instead use your own custom code to copy the form into an iframe and submit it hidden form the user. You then copy the iframes content after the submission and that becomes your response form the server. This is terribly complicated so I recommend searching Stack Overflow and blogs for help. Also, just FYI the "response" you get back from the iFrame is limited in the data (information) you'll get back. You wont have access to the whole XMLHttpRequest response for example.

yangfan0095 commented 6 years ago

https://github.com/ded/reqwest/issues/208 look this , it worked for me .🙂