簡體   English   中英

如何將上傳的文件從 charset=iso-8859-1 轉換為 charset=utf-8?

[英]How to convert uploaded file from charset=iso-8859-1 to charset=utf-8?

當用戶上傳具有 charset=iso-8859-1 的文件時,它帶有問號和亂碼。

我已經看到在線 web 將其成功轉換為 utf-8 - 因此在此轉換后上傳文件后,文件正在正確上傳。 這是 web: https://subtitletools.com/convert-text-files-to-utf8-online

這是我的代碼:

const file = document.getElementById('some-id').files[0];

const reader = new FileReader();

reader.onloadend = event => {
  let data = event.target.result;
  console.log(`[data]:`, data); // question marks / gibberish
}

reader.readAsText(file);

我也嘗試過使用reader.readAsBinaryString但得到的是亂碼而不是問號。

我也嘗試過使用 utf8 庫: https://www.npmjs.com/package/utf8但它沒有用。

我上面提到的網站如何將文件轉換為所需的字符集,使其數據不是問號或亂碼? 順便說一句,Google Drive 也做得很好。

您可以將TextDecoder與您自己的字符集一起使用

var data = new TextDecoder('iso-8859-1').decode(await file.arrayBuffer())

猜猜更難的部分是弄清楚它是什么字符集

如果你沒有使用async/await那么你可以這樣做:

const file = document.getElementById('some-id').files[0];
file.arrayBuffer().then(ab => {
  const data = new TextDecoder('iso-8859-1').decode(ab)
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM