使用Javascript读取客户端文本文件 [英] Reading client side text file using Javascript
问题描述
我想读取一个文件(在客户端)并获取数组中的内容。它只是一个文件。我有以下,它不起作用。 'query_list'
是一个textarea,我想在其中显示文件的内容。
I want to read a file (on the client side) and get the content in an array. It will be just one file. I have the following and it doesn't work. 'query_list'
is a textarea where I want to display the content of the file.
<input type="file" id="file" name="file" enctype="multipart/form-data"/>
<script>
document.getElementById('file').addEventListener('change', readFile, false);
function readFile (evt) {
var files = evt.target.files;
var file = files[0];
var fh = fopen(file, 0);
var str = "";
document.getElementById('query_list').textContent = str;
if(fh!=-1) {
length = flength(fh);
str = fread(fh, length);
fclose(fh);
}
document.getElementById('query_list').textContent = str;
}
</script>
我该怎么办呢?最终我想循环遍历数组并运行一些SQL查询。
How should I go about it? Eventually I want to loop over the array and run some SQL queries.
推荐答案
如果你想使用<读取客户端上的文件a href =https://developer.mozilla.org/en-US/docs/Web/API/FileReader =noreferrer> HTML5的FileReader ,您必须使用Firefox,Chrome或IE 10+。如果这是真的,以下示例将读取客户端上的文本文件。
If you want to read files on the client using HTML5's FileReader, you must use Firefox, Chrome or IE 10+. If that is true, the following example reads a text file on the client.
您的示例尝试使用我从未听说过的fopen(在客户端上)
your example attempts to use fopen that I have never heard of (on the client)
document.getElementById('file').addEventListener('change', readFile, false);
function readFile (evt) {
var files = evt.target.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function(event) {
console.log(event.target.result);
}
reader.readAsText(file)
}
For IE< 10支持你需要调查使用像ADO.Stream这样的ActiveX对象Scripting.FileSystemObject http://msdn.microsoft.com/en-us/library/2z9ffy99(v = vs.85).aspx 但是你会遇到安全问题。如果您运行IE允许所有ActiveX对象(对于您的网站),它应该可以工作。
For IE<10 support you need to look into using an ActiveX Object like ADO.Stream Scripting.FileSystemObject http://msdn.microsoft.com/en-us/library/2z9ffy99(v=vs.85).aspx but you'll run into a security problem. If you run IE allowing all ActiveX objects (for your website), it should work.
这篇关于使用Javascript读取客户端文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!