首页 > 解决方案 > 使用 google drive 将视频流式传输到 html5 播放器

问题描述

我尝试使用谷歌驱动器作为托管视频的地方,但每当我尝试使用视频作为源时,谷歌从不返回任何内容。(甚至没有http响应)

示例视频播放器

<video>
  <source 
    src="https://www.googleapis.com/drive/v3/files/<file_id>/?alt=media&key=<api_key>" 
    type="video/mp4"
  />
</video>

如果我在浏览器中输入 url,它会成功提示我允许下载。

有人知道该怎么做吗?

标签: google-drive-apihtml5-videohttprequest

解决方案


// This works...
<video src="https://www.googleapis.com/drive/v3/files/fileID?alt=media&key=apiKey">

// But, even better if you have access to a worker or can otherwise output the file through a script (and modify resonse headers)
async function getFile(request) {
    let response = await fetch('https://www.googleapis.com/drive/v3/files/fileID?alt=media&key=apiKey', request)
    response = new Response(response.body, response)
    response.headers.set('Accept-Ranges', 'bytes') // Allow seeking, not necessarily enabled by default
    response.headers.set('Content-Disposition', 'inline') // Disable Google's attachment (download) behaviour, display directly in browser or stick into video src instead
    return response
}
addEventListener('fetch', event => {
    event.respondWith(getFile(event.request))
})

推荐阅读