Multer不在http对象之外工作

问题描述 投票:0回答:1

我正在使用multer,它在http对象中工作正常,这里是代码:

server = http.createServer(function(req, res){
  var upload = multer({ storage : multerhelper.storage}).single('userFile');
  upload(req, res, function(err) {
    if(err)
      console.log("Error uploading the file");
  });
});

当我把这段代码放在另一个文件中的http对象之外时,它就不再起作用了。

handlers._users.post = function(req, res, data, callback){
    var upload = multer({ storage : multerhelper.storage}).single('userFile');
    upload(req, res, function(err) {
      if(err)
        console.log("Error uploading the file");
      callback(400, {'Message' : 'Done'});
    });
});

非常感谢您的帮助。

node.js multer
1个回答
0
投票

您可以创建一个具有multer逻辑的文件并导出该文件,以便您可以获得multer功能。例:

const multer = require("multer");

// store the file reference through multer 
const storage = multer.diskStorage({
  destination: function (req, file, callback) {
//Where file should be store
    callback(null, __base + "/public/uploads");
  },
  filename: function (req, file, callback) {
    callback(null, file.originalname);
  }
});

//make sure file is image as the jpeg or png
const fileFilter = (req, file, callback) => {
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png" || file.mimetype === 'application/octet-stream') {
    callback(null, true);
  }
  callback(null, false);
};

export const upload = multer({
  storage,
  limits: {
    fileSize: 1024 * 1024 * 5000
  },
  fileFilter
});

现在导入此文件为

import {
  upload
} from "/filepath";
© www.soinside.com 2019 - 2024. All rights reserved.