【问题标题】:req.file is undefined: uploading images in express using multerreq.file 未定义:使用 multer 快速上传图片
【发布时间】:2021-02-10 00:14:20
【问题描述】:

我正在尝试使用 multer 在快速服务器中上传图像,但是,使用 postman 使用下面的路由上传图像会给出 json 消息 { msg: 'image uploaded successfully' }(即,路由正确到达),但 req.file 给出@ 987654323@。为什么?相关文件结构如下,以确保我正确引用了目标:

-后端
--路由
---上传路由.js
--server.js
-前端
- 上传

上传路由.js

import path from 'path';
import express from 'express';
import multer from 'multer';

const router = express.Router();

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, 'uploads');
  },
  filename(req, file, cb) {
    cb(
      null,
      `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
    );
  },
});

function checkFileType(file, cb) {
  const filetypes = /jpg|jpeg|png/;
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = filetypes.test(file.mimetype);

  if (extname && mimetype) {
    return cb(null, true);
  } else {
    cb('Images only!');
  }
}

const upload = multer({
  storage,
  fileFilter: function (req, file, cb) {
    checkFileType(file, cb);
  },
});

router.post('/', upload.single('image'), (req, res) => {
  console.log(req.file);
  try {
    res.status(200).json({ msg: 'image uploaded successfully' });
  } catch (error) {
    console.error(error.message);
  }
  // res.send(`/${req.file.path}`);
});

export default router;

【问题讨论】:

  • 你是如何从前端上传文件的?是多部分/表单数据吗?
  • 我还没到前端。我现在正在尝试使用邮递员上传图片。我只是向路由http://localhost:5000/api/v1/upload 写入一个 POST 请求,然后在 body 字段中,我在 raw 选项中发送一个空对象 {},在表单数据中我将键指定为 image,值是我要上传的图片,这是我检查的格式之一。

标签: node.js express file-upload


【解决方案1】:

只需检查headerbody form-data 请求,因为如果您在应用文件中有此行,则您的代码是正确的

app.use("/uploads", express.static("uploads"));

请求头

【讨论】:

  • 标题就在图片中。在 server.js 文件中,我使用app.use('/api/v1/uploads', uploadRoutes),其中uploadRoutes 被导入为import uploadRoutes from './routes/uploadRoutes)。还能是什么?
猜你喜欢
  • 2021-05-02
  • 2016-04-14
  • 1970-01-01
  • 2018-08-06
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 2021-10-02
  • 2022-01-18
相关资源
最近更新 更多