Bill
Bill

Reputation: 19308

nodejs formidable detect empty file upload

I am new to nodejs i am learning how to upload files. I am using a middleware called formidable, its awsome, but i would like to find out how to skip empty attachment upload. The script below is ok, but it keep creating empty file which shouldn't happen. Thanks advance for any helps or suggestion.

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);

and here is my form

<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>

Upvotes: 5

Views: 5113

Answers (1)

GPX
GPX

Reputation: 3645

Look at the file.size property, and if it is 0, then the file field is empty.

Upvotes: 5

Related Questions