我将视频文件从服务器流式传输到另一台服务器时出现问题。
我写了这个脚本
var request = require("request"),
express = require("express");
var app = express();
app.get("/cast", function(req, res) {
var url = req.query.video;
res.writeHead(200, {
'Content-Type': 'video/mp4'
});
request({
url: url,
headers: {
Referer: "http://example.com/1706398/" + url
}
})
.on('response', function(response) {
response.on('data', function(data) {
console.log("data chunk received: " + data.length)
});
response.on('end', function(data) {
console.log('Video completed');
});
})
.pipe(res);
});
app.listen(8080);
但视频响应有时有时会被破坏,相反,如果请求的数据写入可写缓冲区并保存为视频文件,则它可以与任何URL一起使用。 我在代码中找不到任何错误或问题,这里有一些网址:
这是我尝试的一些网址: https://gist.github.com/FrancisCan/f2bb86f8ff73b45fa192
谢谢:)
答案 0 :(得分:2)
删除writeHead 200,在流式传输时,应该返回http 206结果(部分内容),而不是http200。我有与你相同的场景(将视频文件从云中的blob容器流式传输到角度应用程序),不需要http200响应。
更新:添加一些关于我如何操作的代码:
AzureStorageHelper.prototype.streamBlob = function streamBlob(req, res, blob, params) {
if(!params){
params.container = container;
}
blob_service.getBlobProperties(params.container, blob, function (error, result, response) {
if(!result) return res.status(404).end();
if(error) return res.status(500).end();
var blobLength = result.contentLength;
var range = req.headers.range ? req.headers.range : "bytes=0-";
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
var end = positions[1] ? parseInt(positions[1], 10) : blobLength - 1;
var chunksize = (end - start) + 1;
var options = {
rangeStart: start,
rangeEnd: end,
}
//this is what's interesting for your scenario. I used to set this up myself but it's is now handled by the Azure Storage NodejsSDK
/*res.writeHead(206, {
'Accept-Ranges': 'bytes',
'Content-Range': "bytes " + start + "-" + end + "/" + blobLength,
'Content-Type': result.contentType,
'Content-Length': chunksize,
'Content-MD5': result.contentMD5,
});*/
var options = {
rangeStart: start,
rangeEnd: end,
}
//this is an API from the Azure Storage nodejsSDK I use. You might want to check the source of this method in github to see how this lib deals with the http206 responses and the piping
blob_service.getBlobToStream(params.container, blob, res, options, function (error, result, response) {
if (error) {
return res.status(500).end();
}
});
});