使用FileReader导入JavaScript文件时,如何保留换行符? [英] How to keep newline characters when I import a javascript file with FileReader?

查看:266
本文介绍了使用FileReader导入JavaScript文件时,如何保留换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用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>

此代码打印

"line1line2"

除了我的文件内容是

line1
line2

我如何获得?

line1\nline2

我尝试了readAsBinaryString和readAsText方法,但没有成功.难道我做错了什么 ? 谢谢

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

FileReader文档

关于JSfiddle的示例 http://jsfiddle.net/yTgp7/

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

该问题仅存在于Mac OS X上的Firefox

The problem exists only on Firefox on mac Os X

推荐答案

这是一个Firefox错误,其文本文件仅以'CR'作为行尾.

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

这与MacOSX无关,但与Firefox有关.如果文件仅包含"CR"而不是"LF"或"CR/LF",则在Windows下您将得到相同的结果.

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'.

您必须将"CR"出现替换为"LF"(或"CR/LF"):

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

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

这是您的jsFiddle的工作版本: http://jsfiddle.net/Y56Tq/3/

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

这篇关于使用FileReader导入JavaScript文件时,如何保留换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆