const http = require('http');
const fs = require('fs');
const filePath = './1.mp4';
const server = http.createServer((req, res) => {
const range = req.headers.range
if (range) {
const stat = fs.statSync(filePath);
const fileSize = stat.size;
const rangeList = range.replace("bytes=", "").split('-');
const bufferSize = 1024 * 1024 * 2;//每次传输的字节数,或设置未为fileSize,让客户端尽可能长的获取字节数
let startPos = parseInt(rangeList[0], 10);
let endPos = startPos + bufferSize;
if (endPos >= fileSize) {
endPos = fileSize - 1;
}
const ContentLength = endPos - startPos + 1;
res.setHeader('Accept-Ranges', 'bytes');
res.setHeader('Content-Range', 'bytes ' + startPos + '-' + endPos + '/' + fileSize);
res.setHeader('Content-Length', ContentLength);
if (endPos == fileSize - 1) {
res.writeHead(206, 'Partial Content', {
'Content-Type': 'video/mp4',
});
} else {
res.writeHead(206, 'Partial Content', {
'Content-Type': 'application/octet-stream',
});
}
var fReadStream = fs.createReadStream(filePath, {
encoding: 'binary',
bufferSize:bufferSize,
start:startPos,
end:endPos
});
fReadStream.on('data', function (chunk) {
res.write(chunk, 'binary');
});
fReadStream.on('end', function () {
res.end();
});
} else {
res.end();
}
});
server.listen(3001);
console.log('server.listen(3001)')
NodeJs实现http 断点续传206
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...