Uploading images with fetch to Express using Multer
我正在尝试将图像上传到Express服务器。我不确定如何执行此操作,但是这是我从MDN,
server.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 | var storage = multer.diskStorage({ destination: './public/users', filename: function (req, file, cb) { switch (file.mimetype) { case 'image/jpeg': ext = '.jpeg'; break; case 'image/png': ext = '.png'; break; } cb(null, file.originalname + ext); } }); var upload = multer({storage: storage}); app.use(upload.single('photo')); app.post('/uploadUserImage', function (req, res) { console.log(JSON.stringify(req.body.photo)) // form fields console.log(req.photo) // form files console.log(req.file) // form files res.send(req.body.photo); }); |
client.js
1 2 3 4 5 6 7 8 | function uploadImage (image) { var formData = new FormData(); formData.append('photo', image); fetch('http://localhost:8080/uploadUserImage/', { method:'POST', body: formData }); } |
当我发出此请求时,
{照片:'[目标文件]'} <---来自console.log(req.body');
未定义<---来自console.log(req.file);
发生错误是因为您明确指定了
要解决文件上传问题,应从
1 2 3 4 5 6 7 8 9 | function uploadImage () { // This assumes the form's name is `myForm` var form = document.getElementById("myForm"); var formData = new FormData(form); fetch('http://localhost:8000/uploadUserImage', { method: 'POST', body: formData }); } |
对我来说,问题是Firebase出现错误,无法使用multer。您需要使用busboy并手动对其进行解析。我还需要从react native imagePicker而不是文件blob附加uri。像这样:
1 2 3 4 5 | data.append('fileData', { uri : pickerResponse.uri, type: pickerResponse.type, name: pickerResponse.fileName }); |