什么是 JavaScript Blob 对象,它为什么有用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29055587/
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
What is a JavaScript Blob object, why is it useful?
提问by robbmj
I recently ran into the JavaScript Blob object, I used it to initialize a web worker where the code was contained within a script tag in the document.
我最近遇到了 JavaScript Blob 对象,我用它来初始化一个 web worker,其中代码包含在文档的脚本标记中。
Based on the MDNdocumentation:
基于MDN文档:
A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format.
Blob 对象表示不可变的原始数据的类文件对象。Blob 表示不一定采用 JavaScript 原生格式的数据。
It sounds like it acts as a sack to put a collection of things into that all share a MIME type. Am I wrong in this opinion, is this opinion incomplete?
这听起来像是将所有共享 MIME 类型的事物集合放入其中的袋子。这个观点我错了,这个观点不完整吗?
Why is the object needed/useful?
为什么需要/有用的对象?
回答by Brent Royal-Gordon
Blob
s aren't terribly useful on their own. What's useful about them is that they work with many calls which are meant to process File
s. The most important of these is URL.createObjectURL()
, which can be used to create a URL you can then use in the href
or src
attributes of HTML tags, @import
statements and url()
values in CSS, etc.
Blob
s 本身并不是非常有用。它们的有用之处在于它们可以处理许多旨在处理File
s 的调用。其中最重要的是URL.createObjectURL()
,它可用于创建一个 URL,然后您可以在HTML 标签的href
或src
属性、CSS 中的@import
语句和url()
值等中使用它。
Basically, Blob
gives JavaScript something like temporary files, and URL.createObjectURL()
lets you treat those blobs as though they were files on a web server.
基本上,Blob
给 JavaScript 提供类似于临时文件的东西,并URL.createObjectURL()
让您将这些 blob 视为 Web 服务器上的文件。
回答by John Blythe
You may need to send through an API where a URL is expecting data that is file-like.
您可能需要通过 API 发送,其中 URL 需要类似文件的数据。
Blobs allow you to construct file like objects on the client that you can pass to apis that expect urls instead of requiring the server provides the file.
Blob 允许您在客户端上构建类似对象的文件,您可以将其传递给需要 url 的 api,而不是要求服务器提供文件。
See more here.