ExpressJS使用Multer和BodyParser

时间:2017-02-03 01:42:19

标签: express multipartform-data multer body-parser

我遇到了一个问题,我有一个带字符串字段和文件上传的混合表单(多文件支持),我发现body-parser无法处理enctype="multipart/form-data"所以multer是更好的中间件使用,但我很好奇是否需要这种类型的表单类型,因为文件上传是使用jQuery处理的,并且在从文件资源管理器上传文件时在单独的路径中。表单上传过程中唯一需要的部分是输出到存储文件的链接。关于我应该做什么的任何建议?我应该嵌套表格吗?

形式:

<form action="/app/blog/create" method="post" enctype="multipart/form-data">
    <input type="date" name="annotationDate" id="annotation-form-date" required>
    <input type="text" name="title">
    <textarea name="body"></textarea>
    <input type="file" id="file-input" name="fileUpload[]" multiple>
    <div class="file-section">
    </div>
    <button type="submit">Create Blog</button>
</form>

BodyParser中间件设置(app.js):

var express = require('express');
var app = express();

/Extract POST Data
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

用于文件上传的JQuery(文件选择时发生POST):

$("#file-input").on('change', function(){
        var files = $(this).get(0).files;
        var formData = new FormData();

        for(var i = 0; i < files.length; i++){
            var file = files[i];
            formData.append('fileUpload', file, file.name);
        }

        $.ajax({
            url: '/app/sign',
            type: 'POST',
            data: formData,
            processData: false,
                contentType: false,
            success: function(data){
                for(var i = 0; i < data.length; i++){
                    console.log('This is the element ' + data[i]);
                    $('.file-section').append("<div class='file-preview'><a href='" + data[i] + "'>" + data[i] + "</a><a href='#' class='remove-file' data-file-link='" + data[i] + "'><span class='glyphicon glyphicon-remove'></a></div>");
                }
            },
            error: function(error){
                console.log('error ' + JSON.stringify(error));
            }
        });
    });

/app/sign的路由(用于文件上传处理):

var multer = require('multer');
var multerS3 = require('multer-s3');
   var upload = multer({
        storage: multerS3({
            s3: s3,
            bucket: options.Bucket,
            contentType: multerS3.AUTO_CONTENT_TYPE,
            acl: options.ACL,
            key: function(req, file, cb){
                var fileNameFormatted = file.originalname.replace(/\s+/g, '-').toLowerCase();
                cb(null, req.user.organizationId + '/' + uploadDate + '/' + fileNameFormatted);
            }
        })
    });

appRoutes.route('/sign')

.post(upload.array('fileUpload', 5), function(req, res){ 

    var uploadedFiles = req.files;

    var s3FilePath = [];

    for (var prop in uploadedFiles){
        console.log(uploadedFiles[prop].key);
        if (app.get('env') === 'production' || app.get('env') === 'staging'){
            s3FilePath = 'https://files.test.com/' + uploadedFiles[prop].key;
        } else {
            s3FilePath.push(uploadedFiles[prop].location);
        }
    }

    res.send(s3FilePath);
});

/app/blog/create(用于创建记录):

.post(function(req, res){
    models.Blog.create({
        date: req.body.date,
        title: req.body.title,
        body: req.body.body,
    }).then(function(){
        return models.File.bulkCreate({
            fileUpload: req.body.upload
        });
    }).then(function(){
        req.flash('info', 'Blog was successfully created.');
        res.redirect('/app');
    });
});

1 个答案:

答案 0 :(得分:0)

添加以下代码

app.use(bodyParser.json({ limit: '50mb' }));

app.use(bodyParser.urlencoded({
   limit: '50mb',
   extended: true,
   parameterLimit: 50000
}));

代替您的app.js中的这段代码

 app.use(bodyParser.urlencoded({
     extended: true
 }));
 app.use(bodyParser.json());