Simulating drag event of files dragged into browser

Viewed 294

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 Answers

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 );

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.

Related