【问题标题】:Read the contents of a "file" object?读取“文件”对象的内容?
【发布时间】:2011-07-09 05:58:45
【问题描述】:

所以我有一个“文件”对象(通过处理从桌面拖放文件来检索)。我可以使用 ajax 将文件发送到服务器,然后将它们返回给 javascript 来处理它们。但是不做这一切就可以读取它的内容吗?

Here, play around with this fiddle. 将任意文件拖到框中并使用变量file

我已经尝试了这个对象的所有方法...没有运气。能不能拿到刚才拖入浏览器的文件内容?

PS:我会像这样将文件发送到服务器:

var ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("returnRawPostData.php");
ajaxRequest.send(file);

我可能在上面的代码中遗漏了一些东西,但这只是因为不再使用纯 JS 来进行 AJAX 调用。

【问题讨论】:

标签: javascript file drag-and-drop


【解决方案1】:

使用 Martin Mally 的链接(非常感谢!),我想出了这个:

var file = e.dataTransfer.files[0],
    read = new FileReader();

read.readAsBinaryString(file);

read.onloadend = function(){
    console.log(read.result);
}

read.result 存放文件内容的位置。

【讨论】:

  • 工作就像一个魅力!谢谢你们!
  • 小心,这是一个异步方法。
【解决方案2】:

我认为这是可能的;查看这两篇文章:

  1. https://developer.mozilla.org/en/Using_files_from_web_applications
  2. http://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/

在上传到服务器之前,它们都通过 JS/HTML 对“已删除”文件进行操作。 (例如调整图片大小等)希望对您有所帮助。

【讨论】:

    【解决方案3】:

    我只是用

    let reader = new FileReader();
    reader.readAsText(your_file_object);
    
    reader.onload = function() {
        console.log(reader.result);  // prints file contents
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-29
      • 2019-02-10
      • 1970-01-01
      • 2011-12-12
      • 2011-04-21
      • 2021-12-25
      • 1970-01-01
      相关资源
      最近更新 更多