如何生成和共享文件?

How to generate and share a file?

我想通过 api web share, but instead of using an uploaded file as in the tutorial demos, I want to use a generated file, similar to what is done in this question.

分享一个 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));

它需要是一个 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 下访问)。