【问题标题】:How to get contents of a file selected with browse button?如何获取使用浏览按钮选择的文件的内容?
【发布时间】:2013-02-23 10:39:55
【问题描述】:

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

这是我在这方面的进展:

    <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

【问题讨论】:

标签: javascript jquery python html dom


【解决方案1】:

使用 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

【讨论】:

  • 我没有看到比我所做的更多的事情。您的代码对我来说很有意义,但在小提琴中它不会输出文件的任何内容!
  • 哦,我明白了,你只为图像连接了它!知道了。现在,我必须只为文本连接它!我看到你从html5rocks.com/en/tutorials/file/dndfiles 那里得到了那个代码
  • @DKean 查看htmlgoodies.com/beyond/javascript/… 中的示例以了解如何读取文本文件
  • 我做了,但它在 FireFox 上失败了。所以这没什么用,因为我的用户大部分时间都使用 FF。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
相关资源
最近更新 更多