【问题标题】:Uploading images with fetch to Express using Multer使用 Multer 将带有 fetch 的图像上传到 Express
【发布时间】:2016-09-25 05:05:41
【问题描述】:

我正在尝试将图像上传到 Express 服务器。我不太确定如何执行此操作,但这是我从 MDN、express、react-dropzone 和 multer 文档中获得的信息。 Multer 似乎没有从 react-dropzone 中获取 FormData 对象,当注销 req.file 时它返回 undefined。

server.js

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

    function uploadImage (image) {
      var formData = new FormData();
      formData.append('photo', image);
      fetch('http://localhost:8080/uploadUserImage/', {
        method:'POST',
         body: formData
      });
    }

当我提出这个请求时,morgan 会注销以下内容:

{ photo: '[object File]' }

未定义

multer 创建文件夹public/uploads,但不将图像放置在该位置。我如何获取照片,因为我需要通过sharp 运行它(压缩文件大小并调整图像大小),然后将其放入uploads 文件夹中?

【问题讨论】:

    标签: node.js express reactjs upload multer


    【解决方案1】:

    发生错误是因为您明确指定了'Content-type'。要正确执行此操作,您还需要指定边界。你可以在这里找到multipart/form-data的详细解释:How does HTTP file upload work?

    要解决文件上传问题,您应该从fetch 请求中删除'Content-Type' 规范。您还可以重构 uploadImage 方法以在不解析输入的情况下上传表单:

    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
      });
    }
    

    【讨论】:

    • 是的,你可以。该图像应位于服务器的uploadUserImage 目录中。
    • 它对我有用,但你应该提到输入的名称必须匹配 multer 的配置 upload.single('photo') 'photo' 在这种情况下
    【解决方案2】:

    对我来说,问题是 firebase 有一个错误,不能使用 multer。您需要使用 busboy 并手动解析它。我还需要从 react native imagePicker 中添加 uri 而不是文件 blob。像这样:

    data.append('fileData', {
      uri : pickerResponse.uri,
      type: pickerResponse.type,
      name: pickerResponse.fileName
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 2016-09-27
      • 2017-05-22
      • 2020-12-25
      • 2018-07-17
      • 1970-01-01
      • 2021-04-16
      相关资源
      最近更新 更多