在javascript中获取上传文件的数据

Posted

技术标签:

【中文标题】在javascript中获取上传文件的数据【英文标题】:get the data of uploaded file in javascript 【发布时间】:2013-05-06 12:00:06 【问题描述】:

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

<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;   

那么我怎样才能得到那个文件里面的数据呢?

【问题讨论】:

***.com/questions/5028931/… 的副本以及大约十几个其他问题。下次请使用搜索框。 不完全。这个问题是关于 AJAX 的。这似乎是“上传文件,以便浏览器可以操作它”。它没有提到将其上传到服务器。 【参考方案1】:

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

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

在本例中,用户选择了一个 HTML 文件。它显示在&lt;textarea&gt;

<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) 
    let files = evt.target.files; // FileList object

    // use the 1st file from the list
    let f = files[0];
    
    let 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>

【讨论】:

【参考方案2】:

您可以使用新的 HTML 5 文件 api 来读取文件内容

https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

但这不适用于所有浏览器,因此您可能需要服务器端后备。

【讨论】:

【参考方案3】:

以下示例显示了FileReader 读取上传文件内容的基本用法。 Here is a working Plunker of this example.

function init() 
  document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);


function handleFileSelect(event) 
  const reader = new FileReader()
  reader.onload = handleFileLoad;
  reader.readAsText(event.target.files[0])


function handleFileLoad(event) 
  console.log(event);
  document.getElementById('fileContent').textContent = event.target.result;
<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
</head>

<body onload="init()">
  <input id="fileInput" type="file" name="file" />
  <pre id="fileContent"></pre>
</body>

</html>

【讨论】:

plunker 加载缓慢【参考方案4】:

blob 本身存在一些新工具,您可以使用这些工具来读取文件内容,作为让您不必使用旧版 FileReader 的承诺

// What you need to listen for on the file input
function fileInputChange (evt) 
  for (let file of evt.target.files) 
    read(file)
  


async function read(file) 
  // Read the file as text
  console.log(await file.text())
  // Read the file as ArrayBuffer to handle binary data
  console.log(new Uint8Array(await file.arrayBuffer()))
  // Abuse response to read json data
  console.log(await new Response(file).json())
  // Read large data chunk by chunk
  console.log(file.stream())


read(new File(['"data": "abc"'], 'sample.json'))

【讨论】:

很好的答案,谢谢!【参考方案5】:

试试这个

document.getElementById('myfile').addEventListener('change', function() 


          var GetFile = new FileReader();
        
           GetFile .onload=function()
                
                // DO Somthing
          document.getElementById('output').value= GetFile.result;
        
        
        
            
            GetFile.readAsText(this.files[0]);
        )
    <input type="file"  id="myfile">


    <textarea id="output"  rows="4" cols="50"></textarea>

【讨论】:

没有必要用类似的答案(就像其他人在这里提供的那样)碰到一个旧的Q。【参考方案6】:

FileReaderJS 可以为您读取文件。您在onLoad(e) 事件处理程序中获取文件内容为e.target.result

【讨论】:

以上是关于在javascript中获取上传文件的数据的主要内容,如果未能解决你的问题,请参考以下文章

如何使用Javascript从文件上传中获取完整路径

javascript 上传文件到阿里云的oss,上传文件成功后怎么获取文件的真实路径?

javascript结合nodejs实现多文件上传

如果上传的文件是 *.avi 或 *.flv 类型,如何在 JavaScript 中获取 *.avi *.flv、*.rmvb 文件的持续时间?

js如何上传文件

JavaScript 超大文件上传解决方案:分片断点上传