我想知道是否可以用Javascript保存一个简单的txt文件,用ANSI编码保存BLOB。
此时,我有一个脚本,它创建一个带有CRLF行尾的txt文件,但使用UTF-8编码。
可以用ANSI编码保存它吗?我需要这个导入txt文件在一个‘旧的’窗口程序,需要ANSI,而不是UTF-8。
下面是我使用的示例:https://jsfiddle.net/UselessCode/qm5AG/
let textFile = null;
function makeTextFile () {
let text = `Some text with nice line endings\nand special characters like é and ü.`;
const data = new Blob([text], {
type: "text/plain",
endings: "native"
});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
}
发布于 2020-02-16 07:03:25
曾经有一个选项使用TextEncoder API从USVStrings编码到任意编码,但这已经从规范和浏览器中删除了。
您需要使用一个库来执行转换。在这里,我将使用不可移除/文本编码
(async()=> {
const text = `Some text with nice line endings\nand special characters like é and ü.`;
const encoding = 'windows-1252'; // a.k.a ANSI
const encoder = new TextEncoder(encoding, {
NONSTANDARD_allowLegacyEncoding: true
});
const data = encoder.encode(text); // `data` is an Uint8Array
const encoded_as_ANSI = new Blob([data]);
// for demo only
const encoded_as_UTF8 = new Blob([text]);
const ANSI_read = await readAsText(encoded_as_ANSI, encoding);
const UTF8_read = await readAsText(encoded_as_UTF8, encoding);
console.log("(ANSI)", ANSI_read);
console.log("(UTF8)", UTF8_read);
})();
function readAsText(blob, encoding) {
return new Promise(res => {
const reader = new FileReader();
reader.onload = e => res(reader.result);
reader.readAsText(blob, encoding);
});
}
<script>window.TextEncoder = null;// force installation of the polyfill</script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding-indexes.js"></script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding.js"></script>
但是,在这个路由中,我们取消了endings选项,因为这只适用于字符串blobParts。
因此,一种方法是首先创建一个utf-8 Blob,带有endings选项,然后将这个UTF-8 blob转换为ANSI:
(async () => {
const text = `Some text with nice line endings\nand special characters like é and ü.`;
const encoding = 'windows-1252'; // a.k.a ANSI
const utf8_blob = new Blob( [text], { endings: "native" } );
const utf_8_txt = await utf8_blob.text();
const encoder = new TextEncoder(encoding, {
NONSTANDARD_allowLegacyEncoding: true
});
const data = encoder.encode(utf_8_txt); // now `data` is an Uint8Array
const encoded_as_ANSI = new Blob([data]);
const read_as_ANSI = await readAsText(encoded_as_ANSI, encoding)
console.log(read_as_ANSI);
})();
function readAsText(blob, encoding) {
return new Promise(res => {
const reader = new FileReader();
reader.onload = e => res(reader.result);
reader.readAsText(blob, encoding);
});
}
<script>window.TextEncoder = null;// force installation of the polyfill</script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding-indexes.js"></script>
<script src="https://cdn.jsdelivr.net/gh/inexorabletash/text-encoding/lib/encoding.js"></script>
https://stackoverflow.com/questions/59840163
复制相似问题