首页 > 解决方案 > 使用 react-native-video 显示视频,使用 GridFSBucket 来自 express

问题描述

我在这里使用 react-native-video 显示视频时遇到了困难。服务器使用 Express,并使用 GridFSBucket 从 mongodb 检索视频。

问题是:来自 GridFSBucket 的视频不会显示。但是当我尝试将视频放在公用文件夹中时,它会显示。

所以,我的猜测是我提供视频的方式有问题。这是我来自服务器的代码:

const bucket = new GridFSBucket(db.original(), { bucketName: "fs" });
const fileDetail = await db.original().collection("fs.files").findOne({_id: idObj});
if (isNullOrUndefined(fileDetail)) {
    throw new NoContentException(`asset not found for id ${id}`);
}

const range = req.headers["range"]
if (range && typeof range === "string") {
    const parts = range.replace(/bytes=/, "").split("-");
    const partialstart = parts[0];
    const partialend = parts[1];

    const start = parseInt(partialstart, 10);
    const end = partialend ? parseInt(partialend, 10) : fileDetail.length - 1;
    const chunksize = (end - start) + 1;

    res.writeHead(206, {
        'Accept-Ranges': 'bytes',
        'Content-Length': chunksize,
        'Content-Range': 'bytes ' + start + '-' + end + '/' + fileDetail.length,
        'Content-Type': fileDetail.contentType
    });

    bucket.openDownloadStream(idObj, {start, end}).pipe(res);
} else {
    res.header('Content-Length', fileDetail.length);
    res.header('Content-Type', fileDetail.contentType);

    bucket.openDownloadStream(idObj).pipe(res);
}

提前感谢您的回答^_^

标签: gridfsreact-native-video

解决方案


我找到了解决方案。

该行:

bucket.openDownloadStream(idObj, {start, end}).pipe(res);

应该:

bucket.openDownloadStream(idObj, {start, end: end - 1}).pipe(res);

推荐阅读