20

この単純な Web サーバー コードを考えると、次のようになります。

console.log('starting');
var server = require('http').createServer();

server.on('connection',function(socket){console.log('*server/connection');});
server.on(
    'request',
    function(request, response){
        console.log('*server/request');
        request.on(
            'data',
            function(chunk){
                console.log('*request/data');
                // <!> How do I abort next data calls from here?
            }
        );
        request.on(
            'readable',
            function(chunk){
                console.log('*request/readable');
                // <!> How do I abort next readable calls from here?
            }
        );
        request.on(
            'end',
            function(){
                console.log('*request/end');
                response.writeHead(200,"OK");
                response.write('Hello');
                response.end();
            }
        );
        request.on('close',function(){ console.log('*request/close'); } );
        request.on('error',function(){ console.log('*request/error'); } );
    }
);
server.on('close',function(){console.log('server/close');});
server.on('checkContinue',function(request, response){console.log('*server/checkContinue');});
server.on('connect',function(request, socket, head){console.log('*server/connect');});
server.on('upgrade',function(request, socket, head){console.log('*server/upgrade');});
server.on('clientError',function(exception, socket){console.log('*server/clientError');});

server.listen(8080);
console.log('started');

POST または FILE が送信されると、my on data 関数が 1 回以上トリガーされます。時々 (巨大な大きなファイルが送信されるように)データ イベントでこれをキャンセルし、ユーザーに対してオン エンド機能をトリガーしたい場合があります(後で「投稿/ファイルが大きすぎます」と表示されます)。どうすればいいのですか?

4

4 に答える 4

0

私は手ごわいをこのように使用します:

var formidable = require('formidable'),
    http = require('http'),
    util = require('util');

var MaxFieldSize = 1000 * 1000,
    MaxFields = 100,
    MaxUploadSize = 8 * 1000 * 1000;


http.createServer (function(req, res) {

    console.log (req.url);
    console.log (req.headers ["content-type"]);

    if (req.url == '/upload')
    {
        var form = new formidable.IncomingForm();

        form.maxFieldsSize = MaxFieldSize;
        form.maxFields = MaxFields;

        form.on ('progress', function (bytesReceived, bytesExpected) {
            //console.log (bytesReceived, bytesExpected);
            if (bytesReceived > MaxUploadSize)
            {
                console.log ('*** TOO BIG');

                // ***HACK*** see Formidable lib/incoming_form.js
                // forces close files then triggers error in form.parse below
                // bonus: removes temporary files
                // --> use throttling in Chrome while opening /tmp in nautilus
                //     and watch the files disappear
                form.__2big__ = true;
                form._error (new Error ('too big'));

                //req.connection.destroy (); --- moved to form.parse
            }
        });

        form.parse (req, function (err, fields, files) {
            if (err)
            {
                console.log ('*** A', err);
                try // just in case something is wrong with the connection, e.g. closed
                {
                    // might not get through?
                    if (form.__2big__)
                    {
                        res.writeHead (413, {"connection": 'close', "content-type": 'text/plain'});
                        res.end ('upload to big');
                    }
                    else
                    {
                        res.writeHead (500, {"connection": 'close', "content-type": 'text/plain'});
                        res.end ('something wrong');
                    }
                    req.connection.destroy ();
                }
                catch (err)
                {
                    console.log ('*** B', err);
                }
            }
            else
            {
                res.writeHead (200, {"content-type": 'text/plain'});
                res.write ('received upload:\n\n');
                //for (let f in files)
                //    console.log (f, files [f]);
                res.end (util.inspect ({fields: fields, files: files}));
            }
        });
    }
    else
    {
        res.writeHead (200, {"content-type": 'text/html'});
        res.end (
            '<html>\
                <head>\
                    <meta charset="UTF-8">\
                    <title>Test Formidable</title>\
                </head>\
                <body>\
                    <form action="/upload" method="POST" enctype="multipart/form-data">\
                        <input type="hidden" name="foo" value="1">\
                        <input type="text" name="fooh" value="2"><br>\
                        <input type="file" name="bar"><br>\
                        <input type="file" name="baz"><br>\
                        <input type="file" name="boo"><br>\
                        <button type="submit">Submit</submit>\
                    </form>\
                </body>\
            </html>'
        );
    }
}).listen(8080);


/* terminal:
    #> node upload
    /upload
    multipart/form-data; boundary=----WebKitFormBoundaryvqt1lXRmxeHLZtYi
    *** TOO BIG
    *** A Error: too big
        at IncomingForm.<anonymous> (/home/marc/Project/node/upload.js:33:18)
        at emitTwo (events.js:106:13)
        at IncomingForm.emit (events.js:191:7)
        at IncomingForm.write (/home/marc/Project/node/node_modules/formidable/lib/incoming_form.js:155:8)
        at IncomingMessage.<anonymous> (/home/marc/Project/node/node_modules/formidable/lib/incoming_form.js:123:12)
        at emitOne (events.js:96:13)
        at IncomingMessage.emit (events.js:188:7)
        at IncomingMessage.Readable.read (_stream_readable.js:387:10)
        at flow (_stream_readable.js:764:26)
        at resume_ (_stream_readable.js:744:3)
*/

于 2016-05-13T04:35:45.013 に答える
0

これが私の解決策です:

var maxSize = 30 * 1024 * 1024;    //30MB
app.post('/upload', function(req, res) {

    var size = req.headers['content-length'];
    if (size <= maxSize) {
        form.parse(req, function(err, fields, files) {
            console.log("File uploading");
            if (files && files.upload) {
                res.status(200).json({fields: fields, files: files});
                fs.renameSync(files.upload[0].path, uploadDir + files.upload[0].originalFilename);
            }
            else {
              res.send("Not uploading");
            }
        });
    }
    else {
        res.send(413, "File to large");
    }

また、応答を取得する前にクライアントのアップロード時間を無駄にする場合は、クライアントの JavaScript で制御します。

if (fileElement.files[0].size > maxSize) {
    ....
}
于 2014-05-08T05:35:00.650 に答える