[英]How can I use UTF-8 in blob type?
我必须通过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。
我试图解决此问题,但我不知道如何解决。
我使用\
搜索来解决此问题,但是当我尝试以第二种方式使用它时,它对我不起作用。
| [object | Blob] |
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;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.