文件转Blob 防盗链

Posted on 2021-01-25 22:16:31
Author: 可乐小可爱メ
1. 背景

一直想研究下 bilibili 视频 blob防盗链的鬼, 今天做个初探吧


2. 代码

直接上代码吧~~

    2.1 后端部分

const Express = require("express")
const app = new Express()
const fs = require("fs")

app.get("/video", (req, res) => {
const { referer } = req.headers
if (referer !== "http://127.0.0.1:8080/") {
return res.send("404")
}
res.header("Access-Control-Allow-Origin", "*")
const file = fs.readFileSync("./cat.mp4")
res.send(file)
})
app.listen(5010)


    2.2 前端部分

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Blob</title>
<style>
video {
width: 300px;
}
</style>
</head>
<body>
<video src="" id="video" controls></video>
</body>
<script>
const vi = document.getElementById("video")
const xhr = new XMLHttpRequest()
xhr.open("GET", "http://localhost:5010/video", true)
xhr.responseType = "blob"
xhr.onload = function (res) {
if (this.status === 200) {
let blob = this.response
vi.src = URL.createObjectURL(blob)
vi.addEventListener(
"loadedmetadata",
function () {
URL.revokeObjectURL(blob)
},
false
)
}
}
xhr.send()
</script>
</html>


3. 分析

    3.1 暂时用到了 window.URL.createObjectURL ;  即 通过ajax 获取后端的 mp4资源 转换成 blob流.

    3.2 后端部分 读取文件 用 pipe管道 防止内存爆, 同时做 referer 验证, 防止通过抓包 直接下载资源.

    3.3 后续在研究下 是否能直接返回blob地址


4. 参考资料

    为什么视频网站的视频链接地址是blob?

当前评论 (1) 登录后评论

ZQHZIT6OA
2021-09-01 15:26:29

你跑过你的代码吗??

URL.revokeObjectURL(blob)之后视频还能播放?

回复
1