如何获取使用浏览按钮选择的文件的内容?

时间:2013-03-08 00:33:04

标签: javascript jquery python html dom

您创建一个浏览按钮,让用户导航目录,直到他选择一个文件。整个路径和文件名出现在Browse按钮组合的文本元素中。那么,我如何打开该文件来提取数据并对其进行操作?

以下是我对此的了解:

    <div id="browseFile" style="z-index: 1; left:-1040px; width:400px">
        <input id="browse4File" name="/static/Import/Example Portfolio 1.csv" type="file" accept="text/plain" maxlength="200" style="left:20px; width: 200px;" /><br/>
        <span style="position:relative;top:72px; left:320px; top:73px;">
            <!--<button type="button" onclick="javascript:importFile()" style="font-size:16px;">Save</button>-->
            <button type="button" onclick="javascript:u=document.getElementById('browse4File').value ;alert(u);" style="font-size:16px;">Save</button>
        </span>
    </div>

Alert()确实显示文件名,但不显示路径。安全问题......没问题!但是我怎么能打开这个文件呢?我把它发送到后端吗?我在我的服务器上使用带有cherrypy的Python。

或者JavaScript可以提取文件的内容吗?

请帮忙......

TIA

DKean

1 个答案:

答案 0 :(得分:2)

使用html 4是不可能的,使用html 5你可以使用file API。查看浏览器support here

例如:

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

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

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

  document.getElementById('files').addEventListener('change', handleFileSelect, false);

演示:Fiddle