req.body是空的,当我尝试用multer上传文件时,req.files不确定

发布于 2025-02-10 08:43:40 字数 1954 浏览 1 评论 0原文

我正在尝试将FormData发送到Nodejs。我将值'id''photo'附加到表单数据。在前端,我可以清楚地看到formData在浏览器的控制台日志中存在,但是在nodejs后端后端后端不确定

const random = Math.floor(Math.random() * 100000) + 10000;
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './client/public/images');
  },
  filename: function (req, file, cb) {
    cb(null, random.toString() + new Date().getTime() + '.jpg');
  },
});

const move = multer({ storage: storage });
const upload = move.single('photo');
router.get('/upload-photo', upload, (req, res) => {
  const id = req.body.id;
  const photo = req.files['photo'][0].filename;
  db.query(
    'UPDATE users SET photo = ? WHERE id = ?',
    [photo, id],
    function (err, rows, fields) {
      if (err) throw err;
      if (rows.length >= 1) {
        rows.map((entry) => {
          const user = {};
          COLUMNS.forEach((c) => {
            user[c] = entry[c];
          });
          const theUser= {
            id: user.id,
            photo: user.photo,
          };
          res.json(theUser);
        });
      } else {
        return res.status(200).json({});
      }
    }
  );
});

函数:

  function photoUpload() {
    const photoData = new FormData();
    photoData.append('id', id);
    photoData.append('photo', photoFile);
    dispatch(uploadPhoto(photoData));
  }

uploadphoto action:

export const uploadPhoto = (photoData) => (dispatch) => {
  axios
    .get(`/api/user/upload-photo`, photoData)
    .then((res) => {
      dispatch(getPhotos());
    })
    .catch((err) => {
      let message = typeof err.response != 'undefined' ? err.response.data : {};
      dispatch({
        type: GET_ERRORS,
        payload: message,
      });
    });
};

我不知道它是否重要,是否重要,但是在另一个API文件中有另一种类似的路线,而且效果很好。这基本上是与唯一区别的代码相同的代码,即另一个路由将多个文件以及多个req.body数据上传。而且一个完美的工作

I'm trying to send FormData to nodeJs. I appended the values 'id' and 'photo' to the form data. In the front-end, I can clearly see that the FormData is there in the browser's console log, but it is undefined in the nodeJs backend

the backend:

const random = Math.floor(Math.random() * 100000) + 10000;
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './client/public/images');
  },
  filename: function (req, file, cb) {
    cb(null, random.toString() + new Date().getTime() + '.jpg');
  },
});

const move = multer({ storage: storage });
const upload = move.single('photo');
router.get('/upload-photo', upload, (req, res) => {
  const id = req.body.id;
  const photo = req.files['photo'][0].filename;
  db.query(
    'UPDATE users SET photo = ? WHERE id = ?',
    [photo, id],
    function (err, rows, fields) {
      if (err) throw err;
      if (rows.length >= 1) {
        rows.map((entry) => {
          const user = {};
          COLUMNS.forEach((c) => {
            user[c] = entry[c];
          });
          const theUser= {
            id: user.id,
            photo: user.photo,
          };
          res.json(theUser);
        });
      } else {
        return res.status(200).json({});
      }
    }
  );
});

The function :

  function photoUpload() {
    const photoData = new FormData();
    photoData.append('id', id);
    photoData.append('photo', photoFile);
    dispatch(uploadPhoto(photoData));
  }

the uploadPhoto action:

export const uploadPhoto = (photoData) => (dispatch) => {
  axios
    .get(`/api/user/upload-photo`, photoData)
    .then((res) => {
      dispatch(getPhotos());
    })
    .catch((err) => {
      let message = typeof err.response != 'undefined' ? err.response.data : {};
      dispatch({
        type: GET_ERRORS,
        payload: message,
      });
    });
};

I don't know if it matters or not, but there is another route like this in a different api file and it works fine. This is basically the same code as that one with the only difference being that the other route uploads multiple files along with multiple req.body data. And that one works perfectly

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

累赘 2025-02-17 08:43:40

而不是:

const photo = req.files['photo'][0].filename;

我必须做:

const photo = req.file.fileName;因为它只是一个文件

Instead of:

const photo = req.files['photo'][0].filename;

I had to do:

const photo = req.file.filename; since it was just only one file

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文