How Can I Use Utf-8 In Blob Type?
I have to export table by csv file. csv file data is from server by Blob type. Blob {size: 2067, type: 'text/csv'} async exportDocumentsByCsv() { this.commonStore.setLoading(
Solution 1:
Blob doesn't take care of the encoding for you, all it sees is binary data. The only conversion it does is if you pass in an UTF-16 DOMString in the constructor's BlobsList
The best in your situation is to set up everything in your application from server to front as UTF-8 and to ensure that everything is sent using UTF-8. This way, you will be able to directly save the server's response, and it will be in UTF-8.
Now, if you want to convert a text file from a known encoding to UTF-8, you can use a TextDecoder, which can decode a ArrayBuffer view of the binary data from a given encoding to DOMString, which can then be used to generate an UTF-8 Blob:
/* const data = await fetch(url)
.then(resp=>resp.arrayBuffer())
.then(buf => new Uint8Array(buf));
*/const data = newUint8Array([147, 111, 152, 94 ]);
// the original data, with Shift_JIS encodingconst shift_JISBlob = newBlob([data]);
saveAs(shift_JISBlob, "shift_JIS.txt");
// now reencode as UTF-8const encoding = 'shift_JIS';
const domString = newTextDecoder(encoding).decode(data);
console.log(domString); // here it's in UTF-16// UTF-16 DOMStrings are converted to UTF-8 in Blob constructorconst utf8Blob = newBlob([domString]);
saveAs(utf8Blob, 'utf8.txt');
functionsaveAs(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;}
Post a Comment for "How Can I Use Utf-8 In Blob Type?"