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

前端 未结 4 1072
予麋鹿
予麋鹿 2021-02-19 07:11

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

相关标签:
4条回答
  • 2021-02-19 07:58

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

    0 讨论(0)
  • 2021-02-19 08:03

    You can write

    event.dataTransfer.setData = ('text', 'tmp.txt');
    
    0 讨论(0)
  • 2021-02-19 08:07

    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.

    0 讨论(0)
  • 2021-02-19 08:13

    You can use the .innerHTML of an <a> element to set the name of linked file

    <div class="container">
      <h1>Drag out any of these links to your dekstop</h1>
      <a href="file.txt" id="dragout" class="dragme" draggable="true">file.txt</a>    
    </div>
    

    where file.txt is a local file dragged into file manager at *nix os which creates a Link to file.txt.

    plnkr http://plnkr.co/edit/pif0ZraAn9RbJI8w2z0w?p=preview

    See also Drag File in Data URI format from Browser to Desktop

    0 讨论(0)
提交回复
热议问题