使用强大的body-parser

时间:2016-07-22 20:28:59

标签: javascript node.js express body-parser formidable

我目前正在尝试添加强大的功能,因此我可以处理包含上传文件(实际上是图片)的表单,我读过评论说两个模块无法一起工作但是this评论这里显示他们两个一起工作。

这是我尝试处理表单的代码

router.post("/", middleware.isLoggedIn, function(req, res){

var form = new formidable.IncomingForm();
console.log(form);
form.uploadDir = "../img";
form.keepExtensions = true;
form.parse(req, function(err, fields, files) {
    if(err){
        console.log(err);
    }
   console.log(fields);
   console.log(files);
});

这些都是我的依赖

var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongo = require("mongoose"),
User = require("./models/user"),
passport = require("passport"),
passportLocal = require("passport-local"),
indexRoutes = require("./routes/index"),
commentRoutes = require("./routes/comments"),
picRoutes = require("./routes/pictures"),
methodOverride = require("method-override"),
formidable = require("formidable");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
mongo.connect("mongodb://localhost/yelp_camp");
app.use(passport.initialize());
app.use(passport.session());
passport.use(new passportLocal(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

这是我在解析

之前记录表单时当前显示的内容
IncomingForm {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
error: null,
ended: false,
maxFields: 1000,
maxFieldsSize: 2097152,
keepExtensions: false,
uploadDir: '/tmp',
encoding: 'utf-8',
headers: null,
type: null,
hash: false,
multiples: false,
bytesReceived: null,
bytesExpected: null,
_parser: null,
_flushing: 0,
_fieldsSize: 0,
openedFiles: [] }

形式:

    <div class="container">
    <div class="row">
        <div class="form">
            <h1>Add new campground</h1>
            <form action="/pictures" method="post">
                <div class="form-group">
                    <label for="name">Give a name to your picture</label>
                    <input class="form-control" id="name" type="text" name="campground[name]" placeholder="Name" autofocus required>
                </div>
                <div class="form-group" id="linkDiv">
                    <label for="link">Paste a direct link to your image</label>
                    <input type="radio" id="link" name="method" value="link"><input class="form-control" id="fileLink" type="text" name="campground[image]" placeholder="Image URL"></input></input>
                </div>
                <div class="form-group" id="uploadDiv">
                    <label for="upload">Or upload the picture</label>
                    <input type="radio" id="upload" name="method" value="upload"><input class="form-control" id="fileUpload" type="file" name="image" value="Upload file" disabled></input></input>
                </div>
                <div class="form-group">
                    <label for="description">Add a description to your picture</label>
                    <input class="form-control" id="description" type="text" name="campground[description]" placeholder="Description">
                </div>
                <div class="form-group">
                    <button class="btn btn-lg btn-primary btn-block">Submit!</button>
                </div>
            </form>
        </div>
    </div>
</div>

但是在那个解析似乎没有运行之后,都没有显示console.log

1 个答案:

答案 0 :(得分:0)

  

两个模块[body-parser and formidable]无法一起工作

但是有效:)我一起使用它们。

在服务器端

// app.js
app.use(require('body-parser').urlencoded({extended: false})); 

// inside upload-router function (req, res, next)
var formidable = require ('formidable');
var fs = require('fs');

var form = new formidable.IncomingForm();
form.uploadDir = '/public/temp/';

form.parse(req, function(err, fields, files) {
    var file = files.file;
    var target = '/public/temp/' + file.name;
    fs.rename(file.path, target, function (err) {   
            if (err) 
                return next(err);
            ...
        });
    });
}

在客户端

<form id = "upload-form" method = "post" >
    <input type="file" id = "upload-input" name = "file" required />
    <input type = "button" onclick = "ajax...">Upload</input>
</form>
...
$.ajax({
    type: 'POST',
    url: '/upload',
    data: new FormData($('#upload-form')[0]),
    enctype: 'multipart/form-data',
    processData: false,
    contentType: false,
    dataType: 'json',
    success: function (data) {
        ...
    }
});