How to save newline characters when importing javascript file using FileReader?

I would like to know how I can get the contents of a file containing special characters with a 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 prints

 "line1line2" 

besides my file contents

 line1 line2 

How can I get?

 line1\nline2 

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

Filereader doc

change

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

enter image description hereenter image description here

The problem only exists in Firefox on mac Os X

+6
source share
1 answer

This is a Firefox bug with a text file containing only “CR” as the end of line.

This does not apply to MacOSX, but Firefox. You have the same result on Windows if your file contains only “CR” instead of “LF” or “CR / LF”.

You need to replace “CR” with “LF” (or “CR / LF”):

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

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

+8
source

Source: https://habr.com/ru/post/954179/


All Articles