node.js中的文件上传只是无限上传?

时间:2011-11-22 08:14:08

标签: node.js file-upload

我正在关注本教程:http://vimeo.com/17442755。 它教您如何使用node.js上传文件。

这是app.js中的完整代码:

var express = require('express');
var multipart = require('./multipart');
var fs = require('fs');

var app = express.createServer();

app.configure(function() {
    app.use(express.logger());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.static(__dirname + '/static'));
});

app.configure('development', function () {
    app.use(express.logger());
    app.use(express.errorHandler({
        dumpExceptions: true,
        showStack: true
    }));
});

app.configure('production', function () {
    app.use(express.errorHandler());
});

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.get('/', function(req, res) {
    res.render('root');
});

var products = require('./products');

app.get('/products', function(req, res) {
    res.render('products/index', {locals: {
        products: products.all
    }});
});

app.get('/products/new', function(req, res) {
    res.render('products/new', {locals: {
        product: req.body && req.body.product || products.new
    }});
});

app.post('/products', function(req, res) {
    var id = products.insert(req.body.product);
    res.redirect('/products/' + id);
});

app.get('/products/:id', function(req, res) {
    var product = products.find(req.params.id);
    res.render('products/show', {locals: {
        product: product
    }});
});

app.get('/products/:id/edit', function(req, res) {
    var product = products.find(req.params.id);
    res.render('products/edit', {locals: {
        product: product
    }});
});

app.put('/products/:id', function(req, res) {
    var id = req.params.id;
    products.set(id, req.body.product);
    res.redirect('/products/'+id);
});

/* Photos */

app.get('/photos/new', function(req, res) {
    res.render('photos/new');
});

app.post('/photos', function(req, res) {
    req.setEncoding('binary');

    var parser = multipart.parser();

    parser.headers = req.headers;

    parser.onPartBegin = function(part) {
        ws = fs.createWriteStream(__dirname + '/static/upload/photos/' + part.filename);
        ws.on('error', function(err) {
            throw err;
        });
    };

    parser.onData = function(data) {
        ws.write(data);
    };

    parser.onPartEnd = function() {
        ws.end();
        parser.close();
        res.send('File sucessfully uploaded.');
    };

    req.on('data', function(data) {
        parser.write(data);
    });

});

app.listen(4000);

现在,当我尝试上传文件时,浏览器会继续加载。

有任何解决此问题的建议吗?

2 个答案:

答案 0 :(得分:3)

您正在使用已被破坏的multipart.js

Current State

Pre-pre-alpha. Almost nothing is here, and what is here is likely completely broken.

If you are asking about this, you probably ought to check out Felix's node-formidable library.

Asaacs(多部分的作者)建议,你应该真的使用node-formidable

答案 1 :(得分:0)

截至目前,它是自动的。如果您使用的是Express或connect.io,请确保在处理POST主体时和使用req.files时。