javascript - 如何生成并共享文件?

标签 javascript html share

我想通过api web share分享一个csv文件,但我想使用生成的文件,而不是像教程演示中那样使用上传的文件,类似于 this question 中所做的操作.

我正在做的是

navigator.share({
    files: [new Blob([data], {type: type})],
    title: 'Vacation Pictures',
    text: 'Photos from September 27 to October 14.',
  })
  .then(() => console.log('Share was successful.'))
  .catch((error) => console.log('Sharing failed', error));

最佳答案

它需要是 File对象,而不仅仅是 Blob:

const file = new File( [ "foo bar" ], "foobar.txt", {type: "text/plain" );

if( navigator.canShare && navigator.canShare( { files: [ file ] } ) ) {
  navigator.share({
    files: [ file ],
    title: 'Dummy text file',
    text: 'Some dummy text file',
  })
  .then( () => console.log( 'Share was successful.' ) )
  .catch( (error) => console.log( 'Sharing failed', error.message ) );
}
else {
  console.log( "can't share this" );
}

但请注意,此 file 成员仅位于 level-2 specs 中,这仍然只是一个草案(可以在 Chrome 中通过 chrome://flags/#enable-experimental-web-platform-features 访问)。

关于javascript - 如何生成并共享文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59314833/

相关文章:

Javascript - 禁用提交按钮,直到 3 个字段不为空

javascript - 将重置按钮拖放到原始位置

android - 如何在 Android 中的其他应用程序选择器 Intent 中以不同的名称列出我的应用程序

html - 使这个 div 响应

php - 简单的 HTML DOM 从标签中获取所有属性

facebook - 通过API在Facebook上分享YouTube视频

javascript - 命名游戏社交分享

javascript - 数据表默认列排序

javascript - 使用 JQuery 获取每个动态添加的索引 DOM 元素的 JSON 响应

javascript - 我可以使用 JavaScript、Flash 或 Silverlight 通过 HTTP 接收流吗?