Multer无法在http对象之外工作

时间:2019-04-23 13:08:42

标签: node.js multer

我正在使用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'});
    });
});

感谢您的帮助。

1 个答案:

答案 0 :(得分: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";