我正在尝试使用fs.createReadStream()在Node.js中传输媒体文件(.mkv)。 这适用于小于2MB的文件,它们正确加载为各自HTML5视频元素的src。
对于大于2MB的媒体文件,这不起作用。他们不加载。 在控制台的“网络”选项卡中,GET请求在转移数据约30KB后显示状态“(已取消)”。 奇怪的是,视频元素似乎显示了媒体文件的正确持续时间。
Request Method:GET
Status Code:206 Partial Content
请求标题
Accept:*/*
Accept-Encoding:identity;q=1, *;q=0
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4,de;q=0.2,el;q=0.2
Connection:keep-alive
Host:(...)
Range:bytes=0-
Referer:yaddayadda
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36
响应标头
Accept-Ranges:bytes
Access-Control-Allow-Headers:origin, content-type
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Length:5716684
Content-Range:bytes 0-5716683/5716684
Content-Type:video/mp4
Date:Tue, 19 Nov 2013 16:29:51 GMT
X-Powered-By:Express
Serverside代码
app.get('/getStream/:u/:f', function(req, res) {
"use strict";
var userId = req.params.u;
var file = req.params.f;
var path = "/tmp/" + userId + "/" + file;
var stat = fs.statSync(path);
var total = stat.size;
if (req.headers['range']) {
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total - 1;
var chunksize = (end - start) + 1;
console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunksize);
var file = fs.createReadStream(path, {start: start, end: end});
res.writeHead(206, {'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4'});
file.pipe(res);
} else {
console.log('ALL: ' + total);
res.writeHead(200, {'Content-Length': total, 'Content-Type': 'video/mp4'});
fs.createReadStream(path).pipe(res);
}
});
Serverside笔记
我尝试使用简单的stream.pipe(res),但问题仍然存在。
我希望我已经提供了足够的信息。
提前致谢