Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML drag/drop - how to set the filename of an *outgoing* drag (to desktop)

I'm trying to make it so a user can drag an icon from the web browser to their desktop, and a text file is created. I've got the content part down, but I can't figure out how to set the filename. I've tried mutating dataTransfer.files but that's read-only. I'm not sure how to achieve this.

class CrashReport extends React.Component {
  dragStart(event) {
    const dat = {name: 'test!', crashDate: new Date()};

    event.dataTransfer.name = 'tmp.txt'; // bad
    event.dataTransfer.setData('text/plain', JSON.stringify(dat, null, 2));
    console.log(event.dataTransfer);
  }

  render() {
    return <div draggable onDragStart={this.dragStart.bind(this)}>
      Drag This
    </div>
  }
}

http://embed.plnkr.co/ar3deFFvedcWhVfwt6c6/

like image 303
ffxsam Avatar asked May 31 '16 23:05

ffxsam


People also ask

How do I make an image draggable in HTML?

To make an object draggable set draggable=true on that element. Just about anything can be drag-enabled: images, files, links, files, or any markup on your page. Our example creates an interface to rearrange columns that have been laid out with CSS Grid.

How do you drag text in HTML?

HTML Drag and Drop (DnD) is a feature of HTML5. It is a powerful user interface concept which is used to copy, reorder and delete items with the help of mouse. You can hold the mouse button down over an element and drag it to another location. If you want to drop the element there, just release the mouse button.


2 Answers

According to this MDN page (emphasis mine)

A local file is dragged using the application/x-moz-file type with a data value that is an nsIFile object. Non-privileged web pages are not able to retrieve or modify data of this type.

So, if you're not writing a browser extension, you can't, and will receive a Security Error.

What happens when you drag some data to the Desktop is up to your OS (mine converts it to some .textClipping file format).

like image 50
Kaiido Avatar answered Oct 04 '22 19:10

Kaiido


Argh! The below works fine in Chrome:

const jsonData = JSON.stringify(dat);
event.dataTransfer.setData("DownloadURL", "application/json:crashdump.json:data:application/json;charset=utf-8," + jsonData);

Though not in Safari nor Firefox. What a huge bummer.

like image 34
ffxsam Avatar answered Oct 04 '22 19:10

ffxsam