简体   繁体   English

使用 fetch、FormData API 和 multer 发送文件:图像不会上传

[英]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).我尝试在获取正文中发送一些 FormData,以使用 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:我试图设置一个 Header "Content-Type": "multipart/form-data"到我的 fetch 调用,但是当我这样做时,我有一个 nodeJS 错误:

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.然后我尝试删除Content-Type header,所以浏览器默认设置它,并且获取失败,我什至没有进入我的nodeJS路由器。

Here is my my FormData preparation method:这是我的FormData准备方法:

 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:这是我的 fetch 调用:

 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'));之前由app.use('/image', require('./controllers/imageController')); so the url of access is http://localhost:8080/image/upload所以访问的 url 是http://localhost:8080/image/upload

response header without Content-Type:没有 Content-Type 的响应 header:

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.我尝试了另一个,它工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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