问题描述:

I'm write an image uploader, and I want to constrain the size of the image to under 3mb. On the server side, I can check the size of the image in the header, something like this (using express):

app.post('/upload', function(req, res) {

if (+req.headers['content-length'] > 3001000) { // About 3mb

// Do something to stop the result

return res.send({'error': 'some kind of error'});

}

// Stream in data here...

}

I tried to stop the req by (and permuations of)

req.shouldKeepAlive = false;

req.client.destroy();

res.writeHead(200, {'Connection': 'close'});

res.end()

None of them really "destroys" the request to prevent more data being uploaded.

req.client.destroy() seem to freeze the download, but the res.send({error... is not being sent back.

Help!

网友答案:

Throw an error and catch it. It will stop the file upload, allowing you to send a response.

try { throw new Error("Stopping file upload..."); } 
catch (e) { res.end(e.toString()); }

It's a bit hackish, but it works...

网友答案:

Here is my solution:

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

And in case of wasting client's uploading time before get response, control it in the client javascript.

if (fileElement.files[0].size > maxSize) {
    ....
}
相关阅读:
Top