首页 > 解决方案 > 使用 node.js '@azure/storage-blob' 包从 Azure-Storage 流式传输视频

问题描述

下面的代码允许使用 node.js 'azure-storage'包从 Azure-Storage 流式传输视频。

我想实现相同的目标,但使用“@azure/storage-blob”包。

.....
app.get("/video", (req, res) => {

    const videoPath = req.query.path;
    
    const blobService = createBlobService();

    const containerName = "videos";

    blobService.getBlobProperties(containerName, videoPath, (err, properties) => { 
        if (err) {
            console.error(`Error occurred getting properties for video ${containerName}/${videoPath}.`);
            console.error(err && err.stack || err);
            res.sendStatus(500);
            return;
        }

        // Writes HTTP headers to the response.

        res.writeHead(200, {
            "Content-Length": properties.contentLength,
            "Content-Type": "video/mp4",
        });

        // Streams the video from Azure storage to the response.

        blobService.getBlobToStream(containerName, videoPath, res, err => {
            if (err) {
                console.error(`Error occurred getting video ${containerName}/${videoPath} to stream.`);
                console.error(err && err.stack || err);
                res.sendStatus(500);
                return;
            }
        });
    });
});

app.listen(PORT, () => {
    console.log(`.....`);
});

提前致谢 ...

标签: node.jsazureexpressvideo-streamingazure-storage

解决方案


好的,我找到了解决方案...

app.get("/video", async (req, res) => {

    try {
        // Create the BlobServiceClient object which will be used to create a container client
        const blobServiceClient = BlobServiceClient.fromConnectionString(
            AZURE_STORAGE_CONNECTION_STRING
        );

        const containerName = 'videos';
        const blobName = req.query.path;

        // Get a reference to a container
        const containerClient = blobServiceClient.getContainerClient(containerName);

        // Get a block blob client
        const blockBlobClient = containerClient.getBlockBlobClient(blobName);

        console.log('\nDownloaded blob content...');

        const downloadBlockBlobResponse = await blockBlobClient.download(0);

        downloadBlockBlobResponse.readableStreamBody.pipe(res);
    } catch (err) {
        console.error(err);
        res.sendStatus(500);
    }

});

推荐阅读