从拖放事件中抓取本地文件并显示它们 [英] Grabbing local files from drag and drop event and displaying them
问题描述
我正在尝试从放置事件中抓取拖放文件并在区域中显示图像,以便用户知道放置成功。但是,我不确定如何抓取那些丢弃的文件并将其显示在某个区域中。我试过这样:
$(e.originalEvent.dataTransfer.files).each(function(){
$(#feedBackAreaTest)。append(< img src ='+ this.name +'/>);
});
然而,它显然只抓住了这个名字。我的问题是,显示图像的正确方法是什么? this.name
只是抓取名称而不是文件的链接。
文件
对象就像牡蛎:你可以在表面上检查它们,但是你不知道它们真正在它们中有什么,直到你撬开它们,看看里面。为此,您需要使用 FileReader
从每个文件
对象中提取数据:
$(e.originalEvent.dataTransfer.files).each(function(){
var reader = new FileReader();
reader.readAsDataURL(this);
reader.onload = function(readEvent){
$(#feedBackAreaTest)。append(< img src ='+ readEvent.target.result +'/>);
}
});
FileReader
对象有一些读取方法,每个方法都采用 Blob
或文件
对象作为参数( readAsText
, readAsDataURL
等)。读取操作完成后, FileReaader
将触发 load
事件,该事件包含刚才读取的文件中的数据。 / p>
I'm attempting to grab dragged and dropped files from the drop event and displaying the images in an area just so the user knows that the drop was successful. However, I'm unsure how to grab those dropped files and display them in an area. I've attempted to that like so:
$(e.originalEvent.dataTransfer.files).each(function(){
$("#feedBackAreaTest").append("<img src='"+this.name+"' />");
});
However, it only grabbed the name, obviously. My question is, what is the right way of displaying the images dropped? this.name
is only grabbing the name and not the link to the file.
File
objects are like oysters: you can inspect them superficially, but you can't know what they really have in them until you pry them open and look inside. To do that, you need to use a FileReader
to extract the data from each File
object:
$(e.originalEvent.dataTransfer.files).each(function(){
var reader = new FileReader();
reader.readAsDataURL(this);
reader.onload = function(readEvent) {
$("#feedBackAreaTest").append("<img src='"+readEvent.target.result+"' />");
}
});
FileReader
objects have a few read methods that each take a Blob
or File
object as an argument (readAsText
, readAsDataURL
, etc.). When the read operation is done, the FileReaader
fires a load
event which has the data from the file just read.
这篇关于从拖放事件中抓取本地文件并显示它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!