我有一份工作请求。我从stackoverflow中取出它。当浏览器向快递节点获取请求时,服务器视频开始播放。但我想将其更改为帖子请求,因为我想选择我想要的视频。所以我想改变玩家视频而不刷新页面。我改变了这个方法发布,我添加了body-parser。这是我的方法:
app.post('/api/video', urlencodedParser , function(req, res) {
var folder = req.body.folder
var path = 'D:/VideoDirectory/'+ folder + '/clip.mp4'
const stat = fs.statSync(path)
const fileSize = stat.size
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, "").split("-")
const start = parseInt(parts[0], 10)
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize-1
const chunksize = (end-start)+1
const file = fs.createReadStream(path, {start, end})
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
}
res.writeHead(206, head)
file.pipe(res)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
}
res.writeHead(200, head)
fs.createReadStream(path).pipe(res)
}
})
这是我的ajax帖子请求:
var folder = {folder: "testFolder"}
$.ajax({
type: 'POST',
url: '/api/video',
data: folder,
success: function(data){
alert('post request sent');
}
});
}
在我发布此帖后请求视频即将进入浏览器。我知道,因为互联网下载管理器试图抓住它。它的文件大小正确。但是这个视频不会转到html5播放器。如何通过此帖子回复为玩家提供信息?我想在不刷新页面的情况下更改视频。这是我的html5视频播放器代码:
<video id="videoPlayer" controls>
<source src="http://xxx.xxx.xx.xx:4000/api/video" type="video/mp4">
</video>
答案 0 :(得分:1)
感谢@btzr,我使用带参数的get请求。这是最后一种形式:
app.get('/api/video/:folder' , function(req, res) {
var streamer = req.params.folder
const path = 'D:/VideoDirectory/' + folder+ '/clip.mp4'
const stat = fs.statSync(path)
const fileSize = stat.size
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, "").split("-")
const start = parseInt(parts[0], 10)
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize-1
const chunksize = (end-start)+1
const file = fs.createReadStream(path, {start, end})
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
}
res.writeHead(206, head)
file.pipe(res)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
}
res.writeHead(200, head)
fs.createReadStream(path).pipe(res)
}
})
我只是用javascript更改视频播放器的src:
var player = document.getElementById('videoPlayer');
player.src = 'http://xxx.xxx.xx.xx:4000/api/video/' + folder;
视频播放器在src更新时向服务器发出请求。