NodeJs服务媒体文件时遇到问题。文件保存在firefox中运行,但Chrome和IE有一些麻烦。
Chrome只能播放一次文件而控件无效。
IE多次播放该文件,但控件不起作用。
对于他们两个我必须实现一个workarround,以便他们将完整地下载文件,流式传输不起作用。我还比较了chrome和firefox的请求标头,它们似乎完全相同。
这是我的代码:
serveFile = (req, res)->
viewType = req.params.viewType
viewName = req.params.folder
fileType = req.params.fileType
fileName = req.params.fileName
res.header("Access-Control-Allow-Origin", "*")
if fileType is 'image'
file = fs.readFileSync(__dirname + "../../../temporary_files/" + viewType + "s/" + viewName + "/ressources/" + fileType + "s/" + fileName )
res.writeHead(200, {'Content-Type': 'image/gif' })
res.end(file, 'binary')
else
if req.headers["user-agent"].indexOf('Chrome') is -1 and req.headers.range isnt undefined
console.log req.headers.range
console.log "-------"
console.log req.headers
fs.readFile(__dirname + "../../../temporary_files/" + viewType + "s/" + viewName + "/ressources/" + fileType + "s/" + fileName, (error, content)->
if error
res.writeHead 500
res.end '<h1>Internal Server Error</h1>'
else
range = req.headers.range
total = content.length
parts = range.replace(/bytes=/, "").split("-")
partialstart = parts[0]
partialend = parts[1]
start = parseInt(partialstart, 10);
end = if partialend then parseInt(partialend, 10) else total
chunksize = (end-start)
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Access-Control-Allow-Origin": "*",
"Content-Length": chunksize,
"Content-Type": fileType + "/" + (if fileName.split(".")[1] is 'mp3' then 'mpeg' else 'mp4')
})
res.end(content.slice(start, end))
)
else
console.log "here"
file = fs.readFileSync(__dirname + "../../../temporary_files/" + viewType + "s/" + viewName + "/ressources/" + fileType + "s/" + fileName )
res.writeHead(200, {'Content-Type': fileType + "/" + (if fileName.split(".")[1] is 'mp3' then 'mpeg' else 'mp4') })
res.end(file, 'binary')
这真让我疯了。我不知道如何解决它。我在媒体标签中尝试了preload-tag而没有结果。
非常感谢您的帮助。