【问题标题】:How can I use UTF-8 in blob type?如何在 blob 类型中使用 UTF-8?
【发布时间】:2019-04-29 14:18:47
【问题描述】:

我必须通过 csv 文件导出表格。

csv 文件数据来自服务器的 Blob 类型。

Blob {size: 2067, type: "text/csv"}
async exportDocumentsByCsv() {
    this.commonStore.setLoading(true)
    try {
      const result = await DocumentSearchActions.exportDocumentsByCsv({
        searchOption: this.documentSearchStore.searchOption
      })

      // first
      // const blob = new Blob([result.body], { type: 'text/csv;charset=utf-8;' })

      // second
      // const blob = new Blob([`\ufeff${result.body}`], { type: 'text/csv;charset=utf-8;' })
      const blob = result.body
      console.log('result.body', result.body)
      const fileName = `document - search - result.csv`
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        // for IE
        window.navigator.msSaveOrOpenBlob(blob, fileName)
      } else {
        FileSaver.saveAs(blob, fileName)
      }
      this.commonStore.setLoading(false)
    } catch (err) {
      alert(err.errorMessage)
      this.commonStore.setLoading(false)
    }
  }

由于我的语言,我必须设置 utf-8 否则。

我试图解决这个问题,但我不知道如何解决它。

我通过使用\ufeff 搜索修复了这个问题,但是当我尝试像这样使用它时 第二种方式,它对我不起作用。

| [object  | Blob]  |

【问题讨论】:

标签: javascript blob


【解决方案1】:

Blob 不会为您处理编码,它看到的只是二进制数据。它所做的唯一转换是在构造函数的 BlobsList 中传入一个 UTF-16 DOMString

在您的情况下,最好的方法是将应用程序中从服务器到前端的所有内容设置为 UTF-8,并确保使用 UTF-8 发送所有内容。这样,您将能够直接保存服务器的响应,并且它将是 UTF-8 格式。

现在,如果您想将文本文件从 已知编码 转换为 UTF-8,您可以使用 TextDecoder,它可以从给定的二进制数据解码 ArrayBuffer 视图编码为 DOMString,然后可用于生成 UTF-8 Blob:

/* const data = await fetch(url)
  .then(resp=>resp.arrayBuffer())
  .then(buf => new Uint8Array(buf));
*/
const data = new Uint8Array([147, 111, 152, 94 ]);
// the original data, with Shift_JIS encoding
const shift_JISBlob = new Blob([data]);
saveAs(shift_JISBlob, "shift_JIS.txt");

// now reencode as UTF-8
const encoding = 'shift_JIS';
const domString = new TextDecoder(encoding).decode(data);

console.log(domString); // here it's in UTF-16


// UTF-16 DOMStrings are converted to UTF-8 in Blob constructor
const utf8Blob = new Blob([domString]);
saveAs(utf8Blob, 'utf8.txt');


function saveAs(blob, name) {
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = name;
  a.textContent = 'download ' + name;
  document.body.append(a);
}
a{display: block;}

【讨论】:

  • Blob {size: 2067, type: "text/csv"} 这是我的抓取结果。我该如何使用它? result.body.arrayBuffer() 发生错误result.body.arrayBuffer is not a function
  • 你需要让你 fetch 返回一个 ArrayBuffer 而不是 Blob,如果你不能,data = await new Response(result.body).arrayBuffer() 会做,甚至FileReader.readAsArrayBuffer。但请注意,您必须知道当前编码才能重新编码。最好直接从您的服务器发送正确的编码。
  • 我不能使用新的响应构造函数。
  • 然后使用 FileReader.readAsArrayBuffer,或者甚至简单地设置您的获取请求以便它直接返回一个 ArrayBuffer,或者甚至更好地设置您的服务器以便它直接以 UTF-8 格式返回文件.
  • 使用FileReaderTextEncoder 解决这个问题,谢谢!
猜你喜欢
  • 2015-09-24
  • 1970-01-01
  • 2017-01-22
  • 2018-01-03
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
相关资源
最近更新 更多