Javascript 读取“文件”对象的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5201317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read the contents of a "file" object?
提问by JCOC611
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?
所以我有一个“文件”对象(通过处理从桌面拖放文件来检索)。我可以使用 ajax 将文件发送到服务器,然后将它们扔回去让 javascript 处理它们。但是,是否有可能在不做这一切的情况下阅读其中的内容?
Here, play around with this fiddle.Drag any file to the box and use the variable file
.
在这里,玩这个小提琴。将任何文件拖到框中并使用变量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:
PS:我会像这样将文件发送到服务器:
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.
我可能在上面的代码中遗漏了一些东西,但这只是因为人们不再使用普通的 JS 来进行 AJAX 调用。
回答by JCOC611
Using the links from Martin Mally(thanks a lot!), I came up with this:
使用Martin Mally的链接(非常感谢!),我想出了这个:
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.
凡read.result
持有该文件的内容。
回答by Martin Maly
I think it's possible; check these two articles:
我认为这是可能的;检查这两篇文章:
- https://developer.mozilla.org/en/Using_files_from_web_applications
- http://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
- https://developer.mozilla.org/en/Using_files_from_web_applications
- 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.
在上传到服务器之前,它们都通过 JS/HTML 操作“删除”的文件。(例如调整图片大小等)我希望它有所帮助。