问题
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