如何使用Node.js的@azure/storage-blob包实现Azure存储视频流传输
基于@azure/storage-blob实现Azure存储视频流式传输方案
原实现使用旧版azure-storageSDK实现视频流返回,以下是适配官方推荐的@azure/storage-blob(v12版本)的实现代码,功能逻辑和原有代码完全对齐:
前置依赖安装
npm install @azure/storage-blob express
完整实现代码
const { BlobServiceClient } = require('@azure/storage-blob'); const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; // 初始化Blob服务客户端,替换原有createBlobService方法 // 建议将连接字符串存储在环境变量中,禁止生产环境硬编码 const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING; const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING); const containerName = "videos"; const containerClient = blobServiceClient.getContainerClient(containerName); app.get("/video", async (req, res) => { const videoPath = req.query.path; if (!videoPath) { return res.sendStatus(400); } try { const blockBlobClient = containerClient.getBlockBlobClient(videoPath); // 获取Blob属性,替换原有getBlobProperties方法 const properties = await blockBlobClient.getProperties(); // 写入响应头,逻辑和原实现一致 res.writeHead(200, { "Content-Length": properties.contentLength, "Content-Type": "video/mp4", }); // 获取Blob可读流并直接pipe到响应,替换原有getBlobToStream方法 const downloadResponse = await blockBlobClient.download(); downloadResponse.readableStreamBody.pipe(res); // 监听流错误 downloadResponse.readableStreamBody.on('error', err => { console.error(`Error occurred getting video ${containerName}/${videoPath} to stream.`); console.error(err.stack || err); res.sendStatus(500); }); } catch (err) { console.error(`Error occurred getting properties for video ${containerName}/${videoPath}.`); console.error(err.stack || err); res.sendStatus(500); } }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
注意事项
- 若需要支持视频拖拽进度、断点续传,可额外解析请求头中的
Range字段,调用download方法时传入偏移量和长度参数返回指定范围的字节流 - 如果使用SAS令牌认证而非连接字符串,可替换
BlobServiceClient.fromConnectionString为BlobServiceClient.fromSasUrl方法初始化客户端
内容的提问来源于stack exchange,提问作者Ali123plus
相关产品推荐
相关产品推荐

