nodejs强大的检测空文件上传

时间:2014-05-21 06:55:54

标签: node.js

我是nodejs的新手,我正在学习如何上传文件。我正在使用一个名为强大的中间件,它很棒,但我想知道如何跳过空附件上传。下面的脚本没问题,但它一直在创建不应该发生的空文件。感谢任何帮助或建议。

var http = require('http');
var user = require('./user');
var fs = require('fs');
var path = require('path');
var url = require('url');
var querystring = require('querystring');
var util = require('util');
var filePath = path.join(__dirname + '/test.html');
var file = fs.readFileSync(filePath, {encoding: 'utf-8'})
var maxData = 2 * 1024 * 1024; //2mb
var connect = require('connect');
var formidable = require('formidable');


http.createServer(function(request, response) {
    if(request.method == 'POST')
    {
        response.writeHead('Content : text/html');
        var incoming = new formidable.IncomingForm();
        incoming.uploadDir = 'upload';
        incoming.on('fileBegin', function(field, file){
            console.log(file.name);
            if (file.name && file.name != ''){
                file.path += "-" + file.name;
                file.name = '';
                console.log(file.name);
            }
        }).on('file', function(filed, file){
            console.log('uploading...');
            response.write(file.name + ' gotted');
        }).on('end', function(){            
            response.end('Eveyrhitng in folder');
        })
        incoming.parse(request);
    }
    if(request.method == 'GET')
    {
        response.writeHead('Content : text/html');
        response.write(file);
        response.end('This is the end of it');
    }
}).listen(8080);

这是我的表格

<html>
    <body>
        <form action="" method="post" enctype="multipart/form-data">
            <!-- <input type="text" name="test">
            <input type="text" name="test2"> -->
            <input type="file" name="file">
            <input type="file" name="file2">
            <input type="submit">
        </form>
    </body>
</html>

1 个答案:

答案 0 :(得分:3)

查看file.size属性,如果是0,则文件字段为空。