Javascript 如何保存 window.URL.createObjectURL() 结果以备将来使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7596515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save the window.URL.createObjectURL() result for future use?
提问by Cokegod
I'm making an application in HTML5 where you choose a video file, and then the application plays it with the HTML5 video
tag and the window.URL.createObjectURL()
. The problem is that I want to save the data about this video in localStorage and play it again when the user uses my application, but as Mozilla MDN statesabout the results of this method:
我正在 HTML5 中创建一个应用程序,您可以在其中选择一个视频文件,然后该应用程序使用 HTML5video
标签和window.URL.createObjectURL()
. 问题是我想将有关此视频的数据保存在 localStorage 中,并在用户使用我的应用程序时再次播放,但正如Mozilla MDN所述:
Browsers will release these automatically when the document is unloaded
当文档被卸载时,浏览器会自动释放这些
So is it possible to do what I'm trying to do? Or do the same thing without the window.URL.createObjectURL()
but with something else?
那么有可能做我想做的事吗?或者在没有window.URL.createObjectURL()
但有其他东西的情况下做同样的事情?
回答by nrabinowitz
I haven't used createObjectURL()
, but if I understand correctly, it's essentially a temporary reference to a file or an in-memory object. If you want to save the actual video, it won't be useful, because the video itself will no longer be referenced by this pointer the next time the user visits the application.
我没有使用过createObjectURL()
,但如果我理解正确的话,它本质上是对文件或内存中对象的临时引用。如果你想保存实际的视频,它不会有用,因为下次用户访问应用程序时,视频本身将不再被这个指针引用。
I thinkyou might be able to do this with a data:
URL instead, as that URL actually includes the full data from the file. This exampledemonstrates using a FileReader
to generate a data URL. I think you should be able to do this:
我认为您可以改为使用data:
URL来执行此操作,因为该 URL 实际上包含文件中的完整数据。此示例演示如何使用FileReader
生成数据 URL。我认为你应该能够做到这一点:
var reader = new FileReader();
reader.onload = function(e) {
var myDataUrl = e.target.result;
// do something with the URL in the DOM,
// then save it to local storage
};
reader.readAsDataURL(file);
Update:If you want to go up to 1GB, as you note in your comment, you'd probably be better served by the FileSystem API. This would require you to get the local file, save a copyof the file to persistent filesystem storage, and then use createObjectURL()
to get a URL for the file copy. You still have a problem with disk space - you just added 1GB of duplicative file content to the user's filesystem - but I don't think it's possible to keep a persistent reference to a file outside of the browser sandbox otherwise.
更新:如果您想增加到 1GB,正如您在评论中指出的那样,FileSystem API可能会更好地为您服务。这将要求您获取本地文件,将文件副本保存到持久文件系统存储,然后用于createObjectURL()
获取文件副本的 URL。您仍然有磁盘空间问题 - 您刚刚向用户的文件系统添加了 1GB 的重复文件内容 - 但我认为否则不可能在浏览器沙箱之外保留对文件的持久引用。