【问题标题】:How to generate and share a file?如何生成和共享文件?
【发布时间】:2019-12-13 01:10:28
【问题描述】:

我想通过 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));

【问题讨论】:

    标签: javascript html share


    【解决方案1】:

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

    【讨论】:

    • 这里的 foo bar text 是什么?这会带来什么?
    • @kb0000 是文件内容,所以这个文件是由“foo bar”组成的文本文件,编码为u​​tf8
    • 那么,当文件已经作为 foobar.txt 提供时,我们是否需要复制或发送文本(如此处的 foo bar)?
    • @kb0000 如果您已经有一个 File 对象,那么您可以省略第一行(只要保存它的变量称为file。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多