2

When you drag files from desktop to browser you can retrieve files as 'FileEntry' using evt.dataTransfer.items[i].webkitGetAsEntry()

However I'm interested is it possible to create this event programatically: to transfer files (blob or created with File constructor) with drag/drop event so that the receiving handler could also extract them exactly the same way?

In my scenario the target might as well be some other site so modification or any kind of different format is not acceptable.

2 Answers2

1

There is DataTransfer constructor, so you can create one very easily, now you just have to add() a File object to its items list:

const dataTransfer = new DataTransfer();
const file = new File( [ "some content" ], "text-file.txt" );
dataTransfer.items.add( file );

const event = new DragEvent( "drop", { dataTransfer } );

ondrop = (evt) => {
  const dT = evt.dataTransfer;
  console.log( dT.items[ 0 ], dT.items[ 0 ].webkitGetAsEntry() );
};

dispatchEvent( event );
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • When I run your code snippet, `dT.items[ 0 ].webkitGetAsEntry()` is logged as `null`. Is there a way to create a DataTransfer object and make `webkitGetAsEntry()` output the FileEntry, as requested in the original question? – brismuth Jan 23 '23 at 05:22
  • Correction - your code appears to work fine on Firefox, but not on Chrome. On Chrome it outputs `null` as I mentioned. Any ideas why, or thoughts on a workaround for Chrome? – brismuth Jan 23 '23 at 05:27
  • @brismuth oh, you're right, seems Chrome changed their behavior. I'll have to check but lack time right now. I'll let you know when I update this answer. – Kaiido Jan 23 '23 at 11:22
  • Oh actually even since M65 it wasn't working on Chrome... I'll have to find something else, and I believe OP was right that using the FileSystem API we should be able to create such a FileEntry object. – Kaiido Jan 23 '23 at 11:38
  • @brismuth Can't find anything simple right now, sorry. Chromium has an issue about it: https://crbug.com/1280560 but, while it's still OPEN, it seems that they don't plan working on it. – Kaiido Jan 25 '23 at 02:42
  • Good find with that open issue, I did quite a bit of googling and didn't find that. This thread was the closest thing I could find. And no worries, thanks for giving it a try! – brismuth Jan 25 '23 at 03:40
-2

If anyone want to achieve the same - yes its possible. By using FileSystem API you can create files in format which is identical to just dragging from your computer.

  • 2
    Can you share a code example, so that this answer may be more useful to readers in the future? – Brad Jan 26 '21 at 04:00