【问题标题】:passing extra info to multer Upload API将额外信息传递给 multer Upload API
【发布时间】:2018-03-29 13:15:27
【问题描述】:

我在node.js中使用multer方式上传,这里详细解释https://ciphertrick.com/2015/12/07/file-upload-with-angularjs-and-nodejs/

我正在尝试使用称为 invoiceId 的请求数据传递另一个信息:

Upload.upload({
                    url: 'http://localhost:4000/api/ubiq/listInvoiceAttachedFiles/attach', //webAPI exposed to upload the file
                    data: {file: file, invoiceId:invoiceId} //pass file as data, should be user ng-model
                }).then(function (resp) { //upload function returns a promise
                    if (resp.data.error_code === 0) { //validate success
                        $window.alert('Success ' + resp.config.data.file.name + ' uploaded');
                        console.log(resp.config.data.file); ....etc

但服务器端的 req.body 为空:

/** API path that will upload the files */

  server.post('/api/ubiq/listInvoiceAttachedFiles/attach', function(req, res) {

    console.log(req.body);

        security.verifyPermission("/api/ubiq/listInvoiceAttachedFiles/attach", req.session.currentUser, true /*isInSession*/).then(function (successInfo) {
            if (!successInfo.isAllowed) {
                console.log('not allowed');
                return res.json(apiHelp.notAllowed());
            }

我做错了什么?

【问题讨论】:

  • 你应该作为 post 参数而不是文件传递
  • Dipak chavda 你的意思是通过 $http.post?
  • 我使用了不同的 multer of diskstorage() 方法,我可以用这种方式发布可能有帮助吗??
  • 为什么不呢,提前谢谢
  • 如果发现任何困难,请查看并告诉我

标签: angularjs node.js multer


【解决方案1】:

Multer 在上传函数的回调中重新附加 body 对象。

您的数据应该在此行之后可用。 https://github.com/rahil471/file-upload-with-angularjs-and-nodejs/blob/master/server/app.js#L35

【讨论】:

  • 哇,Rahil 先生,它比预期的要简单 :)
【解决方案2】:

以下 sn-p 是我的工作代码,我已经在我的应用程序中多次测试和使用过。

Multer 有两个存储引擎:

  1. 磁盘存储
  2. 内存存储

我使用过 DiskStorage,它可以更好地控制文件上的磁盘存储。

var express = require("express");
var app = express()
var router = express.Router();
var multer = require("multer");

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, dirPath);
    },
    filename: function (req, file, cb) {
        var datetimestamp = Date.now() + Math.floor(Math.random() * (1 - 99999999999 + 1)) + 9999999999999;         
        cb(null, datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1].toLowerCase());
    }
});
var infoUpload = multer({storage: storage});

router
        .route(API_PATH)
        .post(infoUpload.array("file"), function (req, res) {
            console.log(req.body);
        });

以下是几个链接,可为您提供简要说明。

http://derpturkey.com/node-multipart-form-data-explained/

http://alexkatz.me/posts/image-upload-with-node-and-multer/

希望它可以帮助解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    相关资源
    最近更新 更多