简体   繁体   English

HTML拖放 - 如何设置*传出*拖动的文件名(到桌面)

[英]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. 我正在努力使用户可以将图标从Web浏览器拖到他们的桌面,并创建一个文本文件。 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. 我尝试过改变dataTransfer.files但这是只读的。 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/ http://embed.plnkr.co/ar3deFFvedcWhVfwt6c6/

According to this MDN page (emphasis mine) 根据这个MDN页面 (强调我的)

A local file is dragged using the application/x-moz-file type with a data value that is an nsIFile object. 使用带有nsIFile对象的数据值的application/x-moz-file类型拖动本地文件。 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 . 因此,如果您没有编写浏览器扩展,则不能,并且将收到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). 将某些数据拖到桌面时会发生什么情况取决于您的操作系统(我将其转换为某种.textClipping文件格式)。

Argh! 哎呀! The below works fine in Chrome: 以下在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. 虽然不在Safari或Firefox中。 What a huge bummer. 真是太糟糕了。

You can use the .innerHTML of an <a> element to set the name of linked file 您可以使用<a>元素的.innerHTML来设置链接文件的名称

<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 . 其中file.txt是一个本地文件,在* nix os中拖入文件管理器,创建了一个Link to file.txtLink to file.txt

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

See also Drag File in Data URI format from Browser to Desktop 另请参阅从数据库URI格式拖动文件从浏览器到桌面

你可以写

event.dataTransfer.setData = ('text', 'tmp.txt');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM