javascriptutf-8html5-filesystemfilesystem-accessfile-system-access-api

Read ANSI files in Web file-system-access API


I am trying to get files using file-system-access API and it works good using this code:

function Process_Files(files) {
    [].map.call(files, async function (file, i) {
        if (isDataFile(file.name)) {
            let fileText = await file.text();
            let filePath = await file.webkitRelativePath;
            ProcessFileContents(await fileText,await filePath);
        }
    })
}
function DirectoryChose(event) {

    let files;
    event.stopPropagation();
    event.preventDefault();


    if (event.type === "change") {
        files = event.target.files;
    }

    if (files) {
        Process_Files(files)
    }
}

dropArea.addEventListener("change", DirectoryChose);

the problem is when we have an ANSI encoded file then the German Characters like Ö, Ü, and Ä become � while it works perfect with UTF-8 encoded files.

I couldn't find anyway to read files using file.text() in ANSI code

thanks for help


Solution

  • You need to use the FileReader() API with the correct encoding. See the MDN docs for details. For example, you could read the data as below:

    // fileOrBlob is a File or a Blob :-) 
    const fileReader = new FileReader();
    fileReader.readAsText(fileOrBlob, 'windows-1252');
    

    The only thing to note is that you need to know the encoding beforehand. If you don't specify an encoding, UTF-8 is assumed.