无法读取multer中未定义的属性“ toString”

时间:2018-11-25 00:28:38

标签: javascript node.js express mustache

我正在使用multer上传文本文件。我需要获取文本文件的内容。因此,我正在使用buffer.toString('utf8')。但是,它给了我一条错误消息,如下所示:Cannot read property 'toString' of undefined。是否有人知道它为什么会发生?另外,我检查了req.file is not undefined

我的代码如下:

const multer  = require('multer');
const upload = multer({ dest: 'uploads/' });
function setupRoutes(app) {
  //@TODO add appropriate routes

  const base = app.locals.base;
    // app.get(`${base}/search.html`, doSearch(app));
    app.get(`${base}/add.html`, createDocsForm(app));
    app.post(`${base}/add.html`, upload.single('file'), doAdd(app));
    app.get(`${base}/:id`, showContent(app));// must be last
  }

function doAdd(app){
  return async function(req, res) {
    try{
       //console.log(req.file.buffer.toString(`utf8`));
      // if(req.file === undefined) console.log("req is undefined");
      const fileContent = req.file.buffer.toString('utf8');
      // const fileContent = req.file;
      let fileName = req.file.originalname;
      fileName = fileName.substring(0, fileName.lastIndexOf('.'));
      const obj = {
        name: fileName,
        content: fileContent
      }
      const a = await app.locals.model.uploadDoc(obj);
      res.redirect(`${app.locals.base}/${fileName}`);
    }catch(err){
        if(req.file == undefined){
          const err = "Select file to upload";
          const model = {base:app.locals.base, err:err};
          const html = doMustache(app,'add',model);
          res.send(html);
        }
        else{
          const errors= wsErrors(err);
          const model = {base:app.locals.base, errors:errors};
          const html = doMustache(app,'add',model);
          res.send(html);
        }
   } }
}

1 个答案:

答案 0 :(得分:2)

您的代码有冲突:

const upload = multer({ dest: 'uploads/' });

如果要使用file.buffer,则需要导入时不使用dest,例如:

const upload = multer({});

您的导入意味着DiskStorage,但multer仅使用buffer在文件上定义MemoryStorage

function Multer (options) {
  if (options.storage) {
    this.storage = options.storage
  } else if (options.dest) {
    this.storage = diskStorage({ destination: options.dest })
  } else {
    this.storage = memoryStorage()
  }

  this.limits = options.limits
  this.preservePath = options.preservePath
  this.fileFilter = options.fileFilter || allowAll
}

请参见multer's storage selection codeMemoryStorage


通过足够的整理,您可以多路复用存储,也许可以通过编写自己的存储多路复用器组合来实现:

class StorageMultiplexer {
    constructor(...storageBackends) {
        this._storages = storageBackends;
    }

    _handleFile(req, file, cb) {
        this._storages.forEach(s => s._handleFile(req, file, cb));
    }

    _removeFile(req, file, cb) {
        this._storages.forEach(s => s._removeFile(req, file, cb));
    }
}

var diskStorage = require('./storage/disk')
var memoryStorage = require('./storage/memory')

const upload = multer({
    dest: 'uploads/',
    storage: new StorageMultiplexer(diskStorage, memoryStorage)
});

此代码未经测试,仅是演示

请阅读StorageEngine.md,以获取更多指导。