在目标文件夹中的上载文件未存储在nodejs中

时间:2018-09-13 09:00:11

标签: javascript node.js multer

controller.js

var multer = require('multer');

var upload = (req, res) => {
    var doc = req.files.file;
    var storage = multer.diskStorage({
        destination:(req,files, cb)=> {
          cb(null, '/uploads')
        },
        filename:(req,files, cb) => {
            var datetimestamp = Date.now();
            cb(null, uploadDoc.originalname);

        }
      })

      var upload = multer({
        storage: multer.memoryStorage()
    }).single('file')


    upload(req, res, function (err) {
        if(err) {
            res.json({ error_code: 1, err_desc: err });
            return;
        }
        res.json({'msg': 'File uploaded successfully!', 'file': req.files.file});


    });
};

module.exports={ upload:upload}

router.js

var express =require("express");
var Router = express.Router();

var Controller = require('../Controllers/Ucontrollers');

Router.route('/upload/file').post(Controller.mediaUpload);

module.exports =Router;

在邮递员中显示结果:

{
    "msg": "File uploaded successfully!",
    "file": {
        "fieldName": "file",
        "originalFilename": "doc.pdf",
        "path": "C:\\Users\\DELL\\AppData\\Local\\Temp\\zwruODmEBT-iWFT0_zDJt8-y.pdf",
        "headers": {
            "content-disposition": "form-data; name=\"file\"; filename=\"doc.pdf\"",
            "content-type": "application/pdf"
        },
        "size": 292202,
        "name": "doc.pdf",
        "type": "application/pdf"
    }
}

但是在目标文件夹中,文档内部什么也没有。在邮递员中成功获取结果,但未存储上载文件夹。

我尝试了一切,但文档没有存储在目的地。在这里我弄错了。

1 个答案:

答案 0 :(得分:0)

从响应中,您可以了解该文件存储在temp文件夹中。

{
    "msg": "File uploaded successfully!",
    "file": {
        "fieldName": "file",
        "originalFilename": "doc.pdf",
        "path": "C:\\Users\\DELL\\AppData\\Local\\Temp\\zwruODmEBT-iWFT0_zDJt8-y.pdf",
        "headers": {
            "content-disposition": "form-data; name=\"file\"; filename=\"doc.pdf\"",
            "content-type": "application/pdf"
        },
        "size": 292202,
        "name": "doc.pdf",
        "type": "application/pdf"
    }
}

问题是,您没有使用磁盘存储。只需在controller.js

中进行以下更改
var upload = multer({
  storage: storage
}).single('file')