首页 > 解决方案 > 同时上传多个图像被损坏

问题描述

尝试使用busboy上传多个文件,文件可能很大所以,我正在异步上传,我正在使用file.on('data')

当我以一些延迟(> 3 秒)连续请求 API 时,该功能工作正常,如果我连续(无延迟)/并行/同时请求 API,则某些图像丢失或损坏。

app.post('/upload', function (req, res) {
    var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        var writeStream = [];
        writeStream[fieldname] = fs.createWriteStream('./tmp/tmp' + Date.now());
        console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
        file.on('data', function (data) {
            console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
            writeStream[fieldname].write(data);
        });
        file.on('end', function () {
            console.log('File [' + fieldname + '] Finished');
            writeStream[fieldname].end();
        });
    });
    busboy.on('finish', function () {
        console.log('Upload complete');
        res.writeHead(200, { 'Connection': 'close' });
        res.end("That's all folks!");
    });
    return req.pipe(busboy);
});

标签: node.jsexpress

解决方案


推荐阅读