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

问题描述 投票:0回答:6

我想上传 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;   
}

那么我如何获取该文件中的数据?

javascript html ajax file-upload
6个回答
73
投票

下面的示例基于 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) {
    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) {
          
          document.querySelector( '#ms_word_filtered_html' ).value = e.target.result ;
        };
      })(f);

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

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

39
投票

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

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

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


34
投票

下面的示例显示了

FileReader
读取上传文件内容的基本用法。 这是本示例的一个工作 Plunker。

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>


14
投票

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


2
投票

试试这个

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>


-1
投票

FileReaderJS可以为您读取文件。您可以在

onLoad(e)
事件处理程序中获取文件内容作为
e.target.result

© www.soinside.com 2019 - 2024. All rights reserved.