5

I'm developing an interactive file-uploader in JavaScript and HTML in which I need to access the currently dragging files filename (the one that triggers the dragenter event).

But there's a problem, the events dataTransfer member does not contain any files, and I really need to know the filename before the drop event is thrown. Is it possible?

Thanks in advance.

mkroman
  • 421
  • 1
  • 5
  • 13
  • 1
    [This is a bug](https://bugs.webkit.org/show_bug.cgi?id=44727) you should be aware of, also [this one](https://bugs.webkit.org/show_bug.cgi?id=42872) – robertc Jan 06 '12 at 18:45

1 Answers1

8

I guess you might have to declare a local variable for it....and remember to initialize it when drag start....kill it when drag end...(dragend/drop)

assign it in "DragStart".....(NOTE: in dragstart u can assign any value to dataTransfer by using "event.dataTransfer.setData"....but it is not accessible in DragEnter/DragOver)

because "DragEnter" can not access dataTransfer.getData() due to security reason... it is ONLY accessible in "onDrop" action.....

see links below: //Get Data can not be used here (for cross frame) due to: http://msdn.microsoft.com/en-us/library/ie/ms536436(v=vs.85).aspx

//use dataTransfer.getData in DragEnter/DragOver doesn't work for Chorme http://code.google.com/p/chromium/issues/detail?id=50009

//dataTransfer.getData is ONLY accessible in DROP for security reason.... http://code.google.com/p/chromium/issues/detail?id=2141

OR you can check on the following link...see if it is helpful: http://weblog.bocoup.com/using-datatransfer-with-jquery-events/

MORE: You can also use localStorage/sessionStorage call, which will save the data into browser cache, localStorage can be used in Cross Window (but same browser), sessionStorage is only accessible of the same session. Just do something like: In your DragStart ->

localStorage.setItem("DraggedFileName",myFileName);

In your DragEnter ->

var myFileName = undefined;
if(localStorage.getItem("DraggedFileName"))
myFileName = localStorage.getItem("DraggedFileName");

In your DropEvent and DragEnd ->

if(localStorage.getItem("DraggedFileName"))
    localStorage.removeItem("DraggedFileName"); //Remove after Drop/DragEnd, clear it

Hope it helps....

Vin.X
  • 4,759
  • 3
  • 28
  • 35
  • 1
    I spent a lot of time trying to figure this out. My conclusion is that the spec as it stands is dumber and dumb. For more details read my explanation (rant) here: http://stackoverflow.com/questions/11927309/html5-dnd-datatransfer-setdata-or-getdata-not-working-in-every-browser-except-fi – Gup3rSuR4c Aug 14 '12 at 19:44
  • Why would you use localStorage for this purpose instead of a variable? – Robo Robok Jun 08 '21 at 21:48