How to keep newline characters when I import a javascript file with FileReader?

老子叫甜甜 提交于 2020-03-18 05:26:05

问题


I'd like to know how I can retrieve the contents of a file keeping special characters with FileReader object.

<form enctype="multipart/form-data">
    <input type="file" id="file" name="file">
</form>
<script>
    $('#file').change(function () {
        var file = document.getElementById('file').files[0];

        var reader = new FileReader();

        reader.onload = function (event) {
            var file_content = event.target.result;
            console.log(file_content);
        }

        reader.readAsBinaryString(file);
    }
</script>

this code print

"line1line2"

except my file content is

line1
line2

How can I get ?

line1\nline2

I tried readAsBinaryString and readAsText methods without any success. Am I doing something wrong ? Thank you

FileReader doc

edit:

an example on JSfiddle http://jsfiddle.net/yTgp7/

The problem exists only on Firefox on mac Os X


回答1:


This is a Firefox bug with text file containing only 'CR' as line ending.

This is not related to MacOSX, but Firefox. You have the same result under Windows if your file only contains 'CR' instead of 'LF or 'CR/LF'.

You have to replace 'CR' occurrences by 'LF' (or 'CR/LF'):

    alert(event.target.result.replace(/\r/g, "\n"));

Here is a working version of your jsFiddle : http://jsfiddle.net/Y56Tq/3/



来源:https://stackoverflow.com/questions/18898036/how-to-keep-newline-characters-when-i-import-a-javascript-file-with-filereader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!