Guillaume Vincent
Guillaume Vincent

Reputation: 14791

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

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/

enter image description here enter image description here

The problem exists only on Firefox on mac Os X

Upvotes: 7

Views: 5243

Answers (1)

C&#233;dric
C&#233;dric

Reputation: 827

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/

Upvotes: 11

Related Questions