简体   繁体   English

我在 react javascript T[] 中有一个对象,需要将其转换为 Blob

[英]I have an object in react javascript T[] and need to convert it to Blob

I am creating this js function:我正在创建这个 js 函数:

export function convertArrayObjToFileDownload(data, filename, filetype = 'application/octet-stream') {
    const blob = new Blob(data, { type: filetype });
    downloadBlob(blob, filename);
}

data is a custom object array, like {Client: 'My Bank', Tasks: 15, Charge Amount: '$300.00' } . data是一个自定义对象数组,例如{Client: 'My Bank', Tasks: 15, Charge Amount: '$300.00' }

I am trying to convert this object array to blob.我正在尝试将此对象数组转换为 blob。 The array could have hundreds of items.该数组可能有数百个项目。

You're very close!你很亲近! Here's the problem:这是问题所在:

The Blob() constructor accepts an Array as the first parameter: Blob()构造函数接受一个数组作为第一个参数:
https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters

And the Array needs to contain a serialized representation of the data you want to store.并且 Array 需要包含您要存储的数据的序列化表示。 For a JavaScript object, that's typically JSON.对于 JavaScript 对象,通常是 JSON。 So first convert your data object to a JSON string, and then store that string in the Blob:因此,首先将您的data对象转换为 JSON 字符串,然后将该字符串存储在 Blob 中:

const json = JSON.stringify(data);
const blob = new Blob([json], { type: 'text/plain;charset=utf-8' })

Since you'll be storing a string, I'd recommend using the text/plain;charset=utf-8 MIME type or application/json for JSON specifically.由于您将存储一个字符串,因此我建议使用text/plain;charset=utf-8 MIME 类型或专门针对 JSON 的application/json

Once you download this Blob, it'll be easy to open in any text editor since it's just plaintext.一旦你下载了这个 Blob,它就很容易在任何文本编辑器中打开,因为它只是纯文本。

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

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