【问题标题】:how to get param from an upload file如何从上传文件中获取参数
【发布时间】:2021-05-04 12:50:23
【问题描述】:

我上传了一张照片,它成功了。但我想再给中间件一个参数。我通过了,但我不明白。我想传递 roomID(在我的例子中是 40)。它不是未定义的!。

我在哪里可以找到房间 ID?

如果我 console.log req.file 那么没有 roomIdent。并且 req.params 为空

但我得到了所有其他参数,例如文件名类型等...

Nodejs 中间件:

const fs = require('fs');
const path = require('path');
const multer = require('multer');

const Storage = multer.diskStorage({
  destination(req, file, callback) {
    callback(null, './uploads');
  },
  filename(req, file, callback) {
    callback(null, `${file.fieldname}_${Date.now()}_${file.originalname}`)
  }
});

module.exports = async (req, res, next) => {
  console.log(req.params);
  let upload = multer({
    storage: Storage
  }).single('photo');

  upload(req, res, err => {
    if(!req.file) {
      return res.json({
        upload: false,
        message: 'Bitte wählen Sie ein Foto oder Video aus.'
      });
    } else if (err instanceof multer.MulterError) {
      return res.json({
        upload: false,
        message: err
      });
    } else if (err) {
      return res.json({
        upload: false,
        message: err
      });
    }

    const allowTypes = ['image/jpeg', 'image/jpg' ,'image/png', 'image/webp', 'image/gif'];
  // Allowed extension
  const extension = path.extname(req.file.originalname);
  const anotherExtension = path.extname(req.file.filename);

  if(extension == '.jpg' || extension == '.jpeg' || extension == '.png' || extension == '.gif'
  || extension == '.webp') {

    if(anotherExtension == '.jpg' || anotherExtension == '.jpeg' || anotherExtension == '.png' || anotherExtension == '.gif'
    || anotherExtension == '.webp') {
  
      if(allowTypes.includes(req.file.mimetype)) {
        req.filename = req.file.filename;
        next();
      }
    }
  }
  });
};

反应原生获取:

const upload = async ({localuri, filename, type, roomIdent}) => {
  try {
    const formData = new FormData();
    formData.append('photo', {
      uri: localuri,
      name: filename,
      type,
      roomid: roomIdent
    });

    const options = {
      headers: {
        'Accept': 'application/json',
        'Content-Type':'multipart/form-data'
      },
      method: 'POST',
      body: formData
    };

    const res = await fetch('http://xxxxx:3000/uploadphoto', options);
    const out = await res.json();
    return out;
  } catch(e) {
    return e;
  }
};

export default upload;

【问题讨论】:

  • 你的问题解决了吗?

标签: node.js react-native multer


【解决方案1】:

对于 RoomID,像这样在 formData 中添加它

const formData = new FormData();
formData.append('photo', {
  uri: localuri,
  name: filename,
  type,
});
formData.append('roomid', roomIdent);
... Now Continue...

然后在后端像这样访问它

console.log(req.body.roomid) // This will log roomId on console

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    相关资源
    最近更新 更多