Read the contents of a “file” object?

本小妞迷上赌 提交于 2019-12-21 07:56:01

问题


So I have a "File" object (retrieved by handling file drag and drop from desktop). I can send the files to the server with ajax, and then throw them back for javascript to handle them. But is it possible to read the contents of it without doing all this?

Here, play around with this fiddle. Drag any file to the box and use the variable file.

I've already tried all of the methods of this object...no luck. Can you get the contents of the file you just dragged into the browser?

PS: I would send the files to the server like this:

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

I might have missed something in the code above, but that's just because one doesn't use plain JS to do AJAX calls anymore.


回答1:


Using the links from Martin Mally (thanks a lot!), I came up with this:

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

read.readAsBinaryString(file);

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

Where read.result holds the contents of the file.




回答2:


I think it's possible; check these two articles:

  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/

They both manipulates with "dropped" file via JS/HTML before uploading to server. (e.g. picture resizing etc.) I hope it helps.



来源:https://stackoverflow.com/questions/5201317/read-the-contents-of-a-file-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!