【问题标题】:get the file which send by the multer in nodejs?获取由nodejs中的multer发送的文件?
【发布时间】:2020-10-30 02:58:47
【问题描述】:

这是我的 upload.js 代码:

var multer = require('multer');
var express = require('express');
const router = express.Router();

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads');
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  },
});

var upload = multer({ storage: storage });

router.post('/', upload.single('file'), (req, res, next) => {
  const file = req.file;
  if (!file) {
    const error = new Error('Please upload a file');
    error.httpStatusCode = 400;
    return next(error);
  }
  res.send(file);
});

module.exports = router;

谁能说出 router.get 是什么?这样我就可以在响应中获得图像。

【问题讨论】:

    标签: node.js express upload multer


    【解决方案1】:

    eol 的回答很好,但是如果你需要保持访问权限,控制器可能看起来像这样:

    res.writeHead(200,{'content-type':'image/jpg'});
    fs.createReadStream('./image/demo.jpg').pipe(res);
    

    【讨论】:

      【解决方案2】:

      您可以简单地 statically serve uploads 文件夹。通过这样做,您不需要实际的get-handler,而是定义express.static-middleware

      app.use(express.static('uploads'));
      

      现在客户端可以简单地向http://yourServer/<imagename>-<timestamp> 执行请求,文件将被自动提供。

      编辑:

      为了将生成的文件名获取到客户端,您可以执行以下操作:

      您可以返回一个包含生成文件名的 json,而不是在您的后处理程序中执行 res.send(file);,然后客户端可以请求:

      app.post("/upload", upload.single('image'), (req, res) => {
          res.json({uploadedFile: req.file.filename})
      });
      

      还有一件事:使用filename-函数会丢失文件的扩展名。为了保留你可以做的扩展(确保requirepath-module):

      filename: (req, file, cb) => {
          const extension = path.extname(file.originalname);
          cb(null, `${file.fieldname}-${Date.now()}${extension}`);
      }
      

      【讨论】:

      • 你告诉我,如果我向邮递员中的/upload 发送获取请求,我将如何获取上传文件夹中的图像。?我的代码:link
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 2016-03-23
      • 2021-10-13
      • 2020-03-04
      相关资源
      最近更新 更多