multer req 文件未定义,但为什么呢?

multer req file is undefined but why?

谁能告诉我为什么我的 req.file 是未定义的? 我添加内容 header 类型, 我添加 single.photo 但我没有得到任何数据

前端:

## data is equal to this:
Object {
  "filename": "3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
  "type": "image/jpg",
  "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/UNVERIFIED-xxxxx-test/ImagePicker/3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
}

const uploadStory = async data => {
  try {
    const form = new FormData();
    form.append('photo', data);
    const options = {
      headers: {
        'Content-Type':'multipart/form-data',
        'Accept':'application/json'
      },
      method: 'POST',
      body: form
    };
    const res = await fetch('http://xxxxxxx.xx:3000/createstory', options);
    const out = await res.json();
    return out;
  } catch(e) {
    console.log(e);
    return e;
  }
};

export default uploadStory;

后端:

const multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function(req, file, cb) {
    console.log(req);
    cb(null, `${file.filename}-${Date.now()}`)
  }
});

const upload = multer({
  storage: storage
}).single('photo');

module.exports = async (req, res, next) => {
  upload(req, res, function(err) {
    if(err) {
      console.log(err)
      return;
    } else if (err instanceof multer.MulterError) {
      console.log(err);
    } else {
      console.log(req.file);
      console.log('hi')
    }
  });
};

................................. ..................................... ..................................... ...................................

确保您的数据对象如下所示

{
    name: "3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
    type: "image/jpg",
    uri: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/UNVERIFIED-xxxxx-test/ImagePicker/3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
}

在您的 data 对象中,您的 keyfilename 而不是 name

把你的upload改成这个

const upload = multer({
  storage: storage,
});

然后,

module.exports = upload.single('photo'), async (req, res) => {
  try {
    console.log(req.body); // Body Here
    console.log(req.file); // File Here
    res.status(500).send('Fetch Completed Successfully');
  } catch (error) {
    console.log(error);
    res.status(500).send('Error');
  }
}