简体   繁体   English

Javascript 将 Blob 对象转换为字符串并返回

[英]Javascript convert a Blob object to an string and back

I have to send a Blob as a String and convert it back to an Blob.我必须将 Blob 作为字符串发送并将其转换回 Blob。 The method blob.text() returns a promise with it's content as a String.方法 blob.text() 返回一个承诺,其内容为字符串。 But how can i convert this string back to a blob?但是如何将此字符串转换回 blob? I want to convert it into an image data url.我想将其转换为图像数据 url。

https://developer.mozilla.org/en-US/docs/Web/API/Blob https://developer.mozilla.org/en-US/docs/Web/API/Blob

To convert a string to a blob, you use the new Blob interface:要将字符串转换为 blob,请使用new Blob接口:

const blob = new Blob([string], {
  type: 'image/jpeg' // or whatever your Content-Type is
});

See this section of the document you linked to .请参阅您链接到的文档的这一部分

If you have a Blob object called blob , blob.type will give its content type.如果您有一个名为blobBlob对象, blob.type将给出其内容类型。 So you could deconstruct and reconstruct it as follows:因此,您可以按如下方式解构和重建它:

const string = await blob.text();
const type = blob.type;
const blob2 = new Blob([string], {type: type});
const base64Data = "dGVRAXXRoZXIUl";

Depending on the format of the base64 string, you might need to prepend content type data.根据 base64 字符串的格式,您可能需要预先添加内容类型数据。 For example, a JPEG image例如,JPEG 图像

const base64Return = await fetch(`data:image/jpeg;base64,${base64Data}`);

Then, convert the response to a blob然后,将响应转换为 blob

const blob = await base64Return.blob();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM