2013-05-12 89 views
21

我想上传一个csv文件并处理该文件中的数据。什么是最好的方法呢?我不喜欢使用PHP脚本。我做了以下步骤。但这种方法只返回文件名而不是文件路径。所以我没有得到所需的输出。在javascript中获取上传文件的数据

<form id='importPfForm'> 
<input type='file' name='datafile' size='20'> 
<input type='button' value='IMPORT' onclick='importPortfolioFunction()'/> 
</form> 

function importPortfolioFunction(arg) { 
    var f = document.getElementById('importPfForm'); 
    var fileName= f.datafile.value; 
} 

那么我怎么能得到该文件中的数据?

+0

重复的http://stackoverflow.com/questions/5028931/is-it-possible-to-read-a-file-using-javascript和大约一打其他问题。请在下次使用搜索框。 – 2013-05-12 14:03:52

+1

不完全。这个问题是关于AJAX的。这似乎是“上传文件,以便浏览器可以操作它”。它没有提到将其上传到服务器。 – 2016-09-15 16:16:36

回答

18

以下示例基于html5rocks解决方案。它使用浏览器的FileReader()函数。只有较新的浏览器。

参见http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files

在这个例子中,用户选择的HTML文件。它上传到<textarea>

<form enctype="multipart/form-data"> 
<input id="upload" type=file accept="text/html" name="files[]" size=30> 
</form> 

<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea> 

<script> 
function handleFileSelect(evt) { 
    var files = evt.target.files; // FileList object 

    // use the 1st file from the list 
    f = files[0]; 

    var reader = new FileReader(); 

    // Closure to capture the file information. 
    reader.onload = (function(theFile) { 
     return function(e) { 

      jQuery('#ms_word_filtered_html').val(e.target.result); 
     }; 
     })(f); 

     // Read in the image file as a data URL. 
     reader.readAsText(f); 
    } 

    document.getElementById('upload').addEventListener('change', handleFileSelect, false); 
</script>