我正在编写Node.js中的程序,用于将文件上传到服务器。在请求处理程序方法中,我使用的是fs.createWriteStream()。它适用于大小小于2 GB的所有文件。但我得到大小为2 GB或更多的文件的RangeError。这是堆栈跟踪:
RangeError: Invalid typed array length
at Buffer.Uint8Array (native)
at FastBuffer (buffer.js:8:1)
at createUnsafeBuffer (buffer.js:33:12)
at allocate (buffer.js:176:12)
at Function.Buffer.allocUnsafe (buffer.js:136:10)
at Function.Buffer.concat (buffer.js:327:23)
at internals.Recorder.collect
我该如何解决?
答案 0 :(得分:0)
server.route({
method: 'POST',
path: '/upload',
config: {
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data',
maxBytes: 2147483648,
timeout: false
},
handler: function (request, reply) {
console.log('Uploading to local server...');
var data = request.payload;
if (!data.asset)
reply({ success: false, errType : 0, msg: 'File not sent' }).type('application/json');
var assetName = data.asset.hapi.filename;
fs.stat(`${__dirname}/uploads`, (err) => {
if (err) {
fs.mkdirSync(`${__dirname}/uploads`);
}
var path = __dirname + "/uploads/" + assetName;
var file = fs.createWriteStream(path);
file.on('error', function (err) {
console.error(new Error(err));
reply({ success: false, errType : 1, msg: err, filename: assetName }).type('application/json');
});
data.asset.pipe(file);
data.asset.on('end', function (err) {
if (err) {
console.error(new Error(err));
reply({ success: false, errType : 1, msg: err, filename: assetName }).type('application/json');
}
这是代码的一部分。有效负载转换为流,然后将其写入文件。