kkangil
kkangil

Reputation: 1746

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(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)
    }
  }

I have to set utf-8 or else because of my language.

I tried to fix this issue, but I don't know how to fix it.

I searched fix this issue by using \ufeff but When I try to use this like second way, It doesn't work for me.

| [object  | Blob]  |

Upvotes: 2

Views: 12180

Answers (1)

Kaiido
Kaiido

Reputation: 136658

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 = 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;}

Upvotes: 1

Related Questions