Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

javascript - Simulating drag event of files dragged into browser

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.

question from:https://stackoverflow.com/questions/65879555/simulating-drag-event-of-files-dragged-into-browser

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...