Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 hereenter image description here

The problem exists only on Firefox on mac Os X

like image 215
Guillaume Vincent Avatar asked Sep 19 '13 14:09

Guillaume Vincent


1 Answers

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/

like image 114
Cédric Avatar answered Sep 30 '22 15:09

Cédric