简体   繁体   中英

Send File with fetch, FormData API and multer : image won't upload

I try to send some FormData in fetch body, to upload image with multer (nodeJS).

I tried to set a Header "Content-Type": "multipart/form-data" to my fetch call, but when I do that, I have a nodeJS error:

Error: Multipart: Boundary not found

I tried then to remove the Content-Type header, so the browser set it by default, and the fetch fails, I even do not enter in my nodeJS router.

Here is my my FormData preparation method:

 handleChange = event => { if(event.target.type === 'file') { const files = event.target.files; var formData = new FormData(); for(var i = 0; i < files.length; i++) { formData.append('images[]', files[i], files[i].name); } //UPLOAD IMAGE METHOD Image.upload(formData); } };

Here is my fetch call:

 upload: async function(formData) { return fetch('http://localhost:8080/image/upload', { method: 'post', body: formData }) }

and here is my controler:

 const express = require('express'); const router = express.Router(); const multer = require('multer'); const upload = multer({dest: __dirname + '/uploads/images'}); router.post('/upload', upload.array('images'), (req, res) => { console.log('req.file', req.file, req.files, req.body); return res.sendStatus(200); }); module.exports = router;

previously routed by app.use('/image', require('./controllers/imageController')); so the url of access is http://localhost:8080/image/upload

response header without Content-Type:

Provisional headers are shown
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryi3lc9wCsnhrvAOAB
Origin: http://localhost:3000
Referer: http://localhost:3000/backoffice/catalog/edit/5d976d6b50fd7f3d008d0f16
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
images[]: (binary)

error with Content-Type:

Error: Multipart: Boundary not found

Thank you all for your brains:) !

Finally, I didn't look at the good place: It was the file I tried to upload that was corrupted. I tried with another one and it worked just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM