jQuery:从文件系统读取文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4408707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: read text file from file system
提问by JohnIdol
I am trying to read a text file using jquery, like this:
我正在尝试使用 jquery 读取文本文件,如下所示:
// LOAD file and split line by line and append divs
$.get('myFile.txt', function(data) {
var lines = data.split("\n");
$.each(lines, function(n, elem) {
$('#myContainer').append('<div>' + elem + '</div>');
});
});
In chrome, I am getting:
在 chrome 中,我得到:
XMLHttpRequest cannot load file:///C:/myPath/myFile.txt. Origin null is not allowed by Access-Control-Allow-Origin.
Firefox shows no error but the code is not executed (I have breakpoints in firebug and the anonymous function never runs).
Firefox 没有显示错误,但代码没有执行(我在 firebug 中有断点,匿名函数从未运行)。
Any help appreciated!
任何帮助表示赞赏!
EDIT:
编辑:
had to:
必须:
- use the file full path
- launch chrome with "--allow-file-access-from-files"
- 使用文件完整路径
- 使用“--allow-file-access-from-files”启动chrome
now it's working OK!
现在它工作正常!
采纳答案by Anders
You can't load a file from your local filesystem, like this, you need to put it on a a web server and load it from there. On the same site as you have the JavaScript loaded from.
您无法从本地文件系统加载文件,像这样,您需要将其放在网络服务器上并从那里加载。在与您加载 JavaScript 的站点相同的站点上。
EDIT: Looking at this thread, you can start chrome using option --allow-file-access-from-files
, which would allow access to local files.
编辑:查看此线程,您可以使用 option 启动chrome --allow-file-access-from-files
,这将允许访问本地文件。
回答by Ali Tarhini
specify the full path of the file url
指定文件url的完整路径
回答by Eric
This is working fine in firefox at least.
这至少在 Firefox 中运行良好。
The problem I was facing is, that I got an XML object in stead of a plain text string. Reading an xml-file from my local drive works fine (same directory as the html), so I do not see why reading a text file would be an issue.
我面临的问题是,我得到了一个 XML 对象而不是纯文本字符串。从我的本地驱动器读取 xml 文件工作正常(与 html 相同的目录),所以我不明白为什么读取文本文件会成为问题。
I figured that I need to tell jquery to pass a string in stead of an XML object. Which is what I did, and it finally worked:
我想我需要告诉 jquery 传递一个字符串而不是一个 XML 对象。这就是我所做的,它终于奏效了:
function readFiles()
{
$.get('file.txt', function(data) {
alert(data);
}, "text");
}
Note the addition of '"text"' at the end. This tells jquery to pass the contents of 'file.txt' as a string in stead of an XML object. The alert box will show the contents of the text file. If you remove the '"text"' at the end, the alert box will say 'XML object'.
请注意在末尾添加了“文本”。这告诉 jquery 将 'file.txt' 的内容作为字符串而不是 XML 对象传递。警报框将显示文本文件的内容。如果删除末尾的“文本”,警告框将显示“XML 对象”。
回答by noahp
A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:
我使用的解决方法是将数据包含为 js 文件,该文件实现了一个将原始数据作为字符串返回的函数:
html:
html:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<script type="text/javascript">
function loadData() {
// getData() will return the string of data...
document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
}
</script>
</head>
<body onload='loadData()'>
<h1>check out the data!</h1>
<div id='data'></div>
</body>
</html>
script.js:
脚本.js:
// function wrapper, just return the string of data (csv etc)
function getData () {
return 'look at this line of data\n\
oh, look at this line'
}
See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=previewThe downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\'
).
在这里查看它的实际效果- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview缺点是您必须对文件进行一些预处理以支持多行(将字符串中的每一行附加到'\n\'
)。
回答by Sreekumar P
this one is working
这个正在工作
$.get('1.txt', function(data) {
//var fileDom = $(data);
var lines = data.split("\n");
$.each(lines, function(n, elem) {
$('#myContainer').append('<div>' + elem + '</div>');
});
});
回答by bfncs
This doesn't work and it shouldn't because it would be a giant security hole.
这不起作用,也不应该,因为这将是一个巨大的安全漏洞。
Have a look at the new File System API. It allows you to request access to a virtual, sandboxed filesystem governed by the browser. You will have to request your user to "upload" their file into the sandboxed filesystem once, but afterwards you can work with it very elegantly.
看看新的文件系统 API。它允许您请求访问由浏览器管理的虚拟沙盒文件系统。您将不得不请求您的用户将他们的文件“上传”到沙盒文件系统中一次,但之后您可以非常优雅地使用它。
While this definitely is the future, it is still highly experimental and only works in Google Chrome as far as CanIUseknows.
回答by exasperated
As long as the file does not need to be dynamically generated, e.g., a simple text or html file, you can test it locally WITHOUT a web server - just use a relative path.
只要文件不需要动态生成,例如,简单的文本或 html 文件,您就可以在没有 Web 服务器的情况下在本地测试它 - 只需使用相对路径。
回答by BlackSpy
If you include a file input box you can access the file as a base64 encoded string by using the FileReader object. If it's a text file a simple base64 decode will work to get the text.
如果包含文件输入框,则可以使用 FileReader 对象以 base64 编码字符串的形式访问文件。如果它是一个文本文件,一个简单的 base64 解码将用于获取文本。
Assuming the following HTML:
假设以下 HTML:
<input type="file" id="myfile" />
You can access using the following JQuery JS:
您可以使用以下 JQuery JS 进行访问:
var file = $('#myfile').get(0).files[0];
var reader = new FileReader();
reader.onload = function (e) {
//get the file result, split by comma to remove the prefix, then base64 decode the contents
var decodedText = atob(e.target.result.split(',')[1]);
//show the file contents
alert(decoded);
};
reader.readAsDataURL(file);
回答by kevin walker
Something like this is what I use all the time. No need for any base64 decoding.
像这样的东西是我一直在使用的。不需要任何 base64 解码。
<html>
<head>
<script>
window.onload = function(event) {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
var fileReader = new FileReader();
fileReader.onload = function(event) {
$('#accessKeyField').val(event.target.result);
}
var file = event.target.files[0];
fileReader.readAsText(file);
document.getElementById('fileInput').value = null;
}
</script>
</head>
<body>
<input type="file" id="fileInput" style="height: 20px; width: 100px;">
</body>
</html>
回答by Cipi
You can't do this without the WEB SERVER!!!Chrome sends XMLHttpRequest to the system that looks something like this
没有 WEB SERVER 就做不到这一点!!!Chrome 将 XMLHttpRequest 发送到看起来像这样的系统
GET /myFile.txt HTTP/1.1
And the operating system is not listening on port 80 to receive this! And even if it is, it must implement HTTP protocol to communicate with the browser...
操作系统没有监听端口 80 来接收这个!而且即使是这样,它也必须实现 HTTP 协议才能与浏览器通信......
To get this working, you must have WEB SERVER installed on your system, that will listen on port 80 and make your files available through a HTTP connection, thus making your code runnable.
要使其正常工作,您必须在系统上安装 WEB SERVER,它将侦听端口 80 并通过 HTTP 连接使您的文件可用,从而使您的代码可运行。