首页 > 解决方案 > 如何生成和共享文件?

问题描述

我想通过api web 共享共享一个 csv 文件,但不是像教程演示中那样使用上传的文件,而是使用生成的文件,类似于在这个问题中所做的。

我正在做的是

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

标签: javascripthtmlshare

解决方案


它需要是一个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成员仅处于2 级规范中,这仍然只是一个草稿(可chrome://flags/#enable-experimental-web-platform-features在 Chrome 中访问)。


推荐阅读