在localStorage中获取并存储一个64mb的mp4文件

Fetching and Storing a 64mb mp4 file in localStorage

本文关键字:一个 64mb 文件 mp4 localStorage 获取 存储      更新时间:2023-09-26

我需要下载大约64mb大小的六个视频,将它们存储在localStorage中,以避免使用数据(不是wifi)再次下载。问题是我执行了以下代码:

var urlVideo = "<link_of_mp4_file>"
var videoStorage = localStorage.getItem("video"),
    videoElement = document.getElementById("video"),
    sourceElement = document.getElementById("source_video");
if (videoStorage) {
    // Reuse existing Data URL from localStorage
    sourceElement.setAttribute("src", videoStorage);
}
else {
    // Create XHR, Blob and FileReader objects
    var xhr = new XMLHttpRequest(),
        blob,
        fileReader = new FileReader();
    xhr.open("GET", urlVideo, true);
    // Set the responseType to arraybuffer. "blob" is an option too, rendering manual Blob creation unnecessary, but the support for "blob" is not widespread enough yet
    xhr.responseType = "arraybuffer";
    xhr.addEventListener("load", function () {
        if (xhr.status === 200) {
            // Create a blob from the response
            blob = new Blob([xhr.response], { type: "video/mp4" });
            // onload needed since Google Chrome doesn't support addEventListener for FileReader
            fileReader.onload = function (evt) {
                // Read out file contents as a Data URL
                var result = evt.target.result;
                // Set image src to Data URL
                videoElement.setAttribute("src", result);
                // Store Data URL in localStorage
                try {
                    localStorage.setItem("video", result);
                }
                catch (e) {
                    console.log("Storage failed: " + e);
                }
            };
            // Load blob as Data URL
            fileReader.readAsDataURL(blob);
        }
    }, false);
    // Send XHR
    xhr.send();
}

在测试了这个脚本之后,我可以从浏览器看到mp4文件正在下载,但是当它完成将视频保存在localStorage中的任务时,它会向我抛出以下错误:

Storage failed: QuotaExceededError: failed to execute 'setItem' on 'Storage': Setting the value of 'video' exceeded the quota.

如何在localStorage中存储这些文件?

您可以启动铬,铬与--unlimited-storage标志设置。


虽然注意,因为--unlimited-storage设置可能在chrome,铬,如果你使用这些浏览器,你可以用requestFileSystem代替FileReader创建的data URI

长度限制

虽然Firefox基本上支持数据uri无限长度,浏览器不需要支持任何特定的数据的最大长度。例如,Opera 11浏览器限制数据uri减少到65000个字符。

File对象存储在LocalFileSystem中,而不是将localStorage存储为字符串。

  • 如何使用webkitRequestFileSystem在file: protocol

  • jQuery文件上传插件:是否可以保留上传文件夹的结构?

  • 如何写在文件(用户目录)使用JavaScript?