我使用节点js multer遇到文件上传问题

时间:2020-04-13 12:43:15

标签: javascript node.js multer

我想使用Postman向下面提到的node js api发送请求,但是找不到文件名。 var file = I get errors in these parts. req.files;var fileName = file.name;如何解决问题?

POSTMAN request

日志

body: [Object: null prototype] {
    title: 'Test PDF Sign via Node Server POSTMAN',
    subject: 'Test PDF Sign via Node Server POSTMAN',
    message: 'Please sign this pdf. POSTMAN',
    email_address: 'xxx@gmail.com',
    name: 'Mr. XXX'
  },
  route: Route {
    path: '/sign',
    stack: [ [Layer], [Layer] ],
    methods: { post: true }
  },
  file: {
    fieldname: 'file',
    originalname: 'nda.pdf',
    encoding: '7bit',
    mimetype: 'application/pdf',
    destination: './tosign',
    filename: 'nda.pdf',
    path: 'tosign/nda.pdf',
    size: 121522
  },
  [Symbol(kCapture)]: false
}
TypeError: Cannot read property 'name' of undefined
    at /Desktop/nodejs/helloSignDemo/routes/index.js:85:25
    at Layer.handle [as handle_request] (/Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/layer.js:95:5)
    at next (/Desktop/nodejs/helloSignDemo/node_modules/express/lib/router/route.js:137:13)
    at Immediate.<anonymous> (/Desktop/nodejs/helloSignDemo/node_modules/multer/lib/make-middleware.js:53:37)
    at processImmediate (internal/timers.js:458:21)

签名请求API

const fs = require('fs');
const multer = require('multer');

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, './tosign');
    },
    filename: function (req, file, cb) {
        cb(null , file.originalname);
    }
});

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


router.post('/sign', upload.single('file'), (req,res)=>{

    res.send('Sign request is called');
    console.log('Sign request is called');

    console.log(req);

    var title = req.title;
    var subject = req.subject;
    var message = req.message;
    var email_address = req.email_address;
    var name = req.name;
    var file = req.files;
    var fileName = file.name;

    console.log(fileName);

    const opts = {
        test_mode: 1,
        title: title,
        subject: subject,
        message: message,
        signers: [
            {
                email_address: email_address,
                name: name
            }
        ],

        files: ['./tosign/'+fileName]
    };

    console.log(opts);

    hellosign.signatureRequest.send(opts).then((res) => {
        console.log(res);
        console.log('Signature Request Id: '+signatureRequestId);
    }).catch((err) => {
        console.log(err)
    });
});

2 个答案:

答案 0 :(得分:0)

请尝试var file = req.file;,因为您要发送的文件不是邮递员正文中的文件

答案 1 :(得分:0)

这是因为name对象中没有file字段。
将您的代码更改为var fileName = file.originalname;