假设我的网站上有一个 video
元素:
<video src="/video.mp4" controls="" id="video"></video>
如何通过将原始源 文件 (/video.mp4
) 转换为单 session Blob URL 来保护它?
我看到一些帖子说它需要用 JavaScript 来完成,尽管它们都没有真正扩展解释如何做的必要细节(或者你可以在哪里找到如何做) .
那么,对于这样的事情,最好的方法是什么?
最佳答案
这是一个快速而肮脏的例子。希望对您有所帮助。
确保查看所有正在使用的方法的文档并检查它们的浏览器支持。不过,这不会保护您的视频不被下载。
// Request the video using a new XMLHttpRequest() with the
// responseType set to blob.
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(){
var reader = new FileReader();
reader.onloadend = function(){
// Pass this string to atob to decode the base-64 encoded string to a string
// representing each byte of binary data.
var byteCharacters = atob(reader.result.slice(reader.result.indexOf(',') + 1));
// Now you can create an array of byte values using charCodeAt and looping
// over the byte string.
var byteNumbers = new Array(byteCharacters.length);
for(var i = 0; i < byteCharacters.length; i++){
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
// Pass the resulting array to Uint8Array to create a typed array of
// 8-bit, unsigned integers.
var byteArray = new Uint8Array(byteNumbers);
// This can then can be passed to the Blob constructor.
var blob = new Blob([byteArray], {type: 'video/ogg'});
// Now that you have a blob, you can pass it to the createObjectURL method.
var url = URL.createObjectURL(blob);
// The resulting URL can be attached to the src attribute of your video.
document.getElementById('video').src = url;
}
// Pass the response to the FileReader using readAsDataURL.
// This will give you a base-64 encoded string representation of the file.
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', 'https://upload.wikimedia.org/wikipedia/commons/c/c0/Roaring_Burps.ogg');
xhr.send();
<video controls="" id="video"></video>
关于javascript - 将视频 src 转换为单 session blob url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41184900/