Web Share API

前言

网页内容如果要分享到其他应用,通常要自己实现分享接口,逐一给出目标应用的连接方式。这样很麻烦,也对网页性能有一定影响。Web Share API 就是为了解决这个问题而提出的,允许网页调用操作系统的分享接口,实质是 Web App 与本机的应用程序交换信息的一种方式。

概述

这个 API 不仅可以改善网页性能,而且不限制分享目标的数量和类型。社交媒体应用、电子邮件、即时消息、以及本地系统安装的、且接受分享的应用,都会出现在系统的分享弹窗,这对手机网页尤其有用。另外,使用这个接口只需要一个分享按钮,而传统的网页分享有多个分享目标,就有多少个分享按钮。

目前,桌面的 Safari 浏览器,手机的安卓 Chrome 浏览器和 iOS Safari 浏览器,支持这个 API。

这个 API 要求网站必须启用 HTTPS 协议,但是本地 Localhost 开发可以使用 HTTP 协议。另外,这个 API 不能直接调用,只能用来响应用户的操作(比如click事件)。

web share API用法

navigator.canShare()

返回指示指定数据是否可共享的布尔值。
这个方法是判断该浏览器支不支持分享,如果支持分享,则返回true,否则就返回false。
列如:

if (!navigator.canShare) {
  //不支持
} else if (navigator.canShare(shareData)) {
  //支持分享
}

也可以这样:

if (navigator.share) {
  // 支持
} else {
  // 不支持
}

navigator.share(data)

分享url

navigator.share是一个函数方法,接受一个配置对象作为参数。

navigator.share({
  title: '分享的标题',
  url: '分享的url地址',
  text: '分享的文本'
})

配置对象有三个属性,都是可选的,但至少必须指定一个。

  • title:分享文本的标题
  • url::分享文本的url链接
  • text:分享文本的内容

一般来说,url是当前网页的网址,title是当前网页的标题,可以采用下面的写法获取。

const title = document.title;
const url = document.querySelector('link[rel=canonical]') ?
  document.querySelector('link[rel=canonical]').href :
  document.location.href;

navigator.share的返回值是一个 Promise 对象。这个方法调用之后,会立刻弹出系统的分享弹窗,用户操作完毕之后,Promise 对象就会变为resolved状态。

navigator.share({
  title: 'WebShare API Demo',
  url: 'url链接'
}).then(() => {
  console.log('Thanks for sharing!');
}).catch((error) => {
  console.error('Sharing error', error);
});

这个可以用async await来实现同步处理。
例如:

html
<p><button>Share url!</button></p>
<p class="result"></p>
JavaScript
const shareData = {
  title: "标题",
  text: "文本",
  url: "url链接",
};

const btn = document.querySelector("button");
const resultPara = document.querySelector(".result");

// Share must be triggered by "user activation"
btn.addEventListener("click", async () => {
  try {
    await navigator.share(shareData);
    resultPara.textContent = "MDN shared successfully";
  } catch (err) {
    resultPara.textContent = `Error: ${err}`;
  }
});

分享file

上面是分享链接的,接下来分享文件类型。
先使用navigator.canShare()方法,判断一下目标文件是否可以分享。因为不是所有文件都允许分享的,目前图像,视频,音频和文本文件可以分享。

if (navigator.canShare && navigator.canShare({ files: filesArray })) {
  // ...
}

上面代码中,这里的关键是files属性,它的值是一个FileList实例对象。

例如:

html
<div>
  <label for="files">Select images to share:</label>
  <input id="files" type="file" accept="image/*" multiple />
</div>
<button id="share" type="button">Share your images!</button>
<output id="output"></output>

JavaScript
const input = document.getElementById("files");
const output = document.getElementById("output");

document.getElementById("share").addEventListener("click", async () => {
  const files = input.files;

  if (files.length === 0) {
    output.textContent = "No files selected.";
    return;
  }

  // feature detecting navigator.canShare() also implies
  // the same for the navigator.share()
  if (!navigator.canShare) {
    output.textContent = `Your browser doesn't support the Web Share API.`;
    return;
  }

  if (navigator.canShare({ files })) {
    try {
      await navigator.share({
        files,
        title: "Images",
        text: "Beautiful images",
      });
      output.textContent = "Shared!";
    } catch (error) {
      output.textContent = `Error: ${error.message}`;
    }
  } else {
    output.textContent = `Your system doesn't support sharing these files.`;
  }
});

最后,还想要具体用法,参考一下链接:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Share_API

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在 .NET 6 WebAPI 中实现文件下载,您可以使用以下步骤: 1. 创建一个 API 端点来处理文件下载请求: ```c# [HttpGet] [Route("download")] public async Task<IActionResult> Download(string fileName) { // 将文件读取到内存流中 MemoryStream memoryStream = new MemoryStream(); using (FileStream fileStream = new FileStream(fileName, FileMode.Open)) { await fileStream.CopyToAsync(memoryStream); } memoryStream.Position = 0; // 将内存流作为响应返回 return File(memoryStream, "application/octet-stream", Path.GetFileName(fileName)); } ``` 2. 在客户端发出 POST 请求,并将文件名作为请求体发送: ```c# var client = new HttpClient(); var response = await client.PostAsync("http://localhost:5000/download", new StringContent("fileName.txt")); ``` 注意,请求体可以是任何有效的字符串,只要您在 API 控制器中使用相应的参数名称来接收它即可。 3. 在客户端处理响应,并将响应内容写入本地文件: ```c# if (response.IsSuccessStatusCode) { using (var stream = await response.Content.ReadAsStreamAsync()) using (var fileStream = new FileStream("fileName.txt", FileMode.Create, FileAccess.Write, FileShare.None)) { await stream.CopyToAsync(fileStream); } } ``` 这将从响应流中读取文件数据,并将其写入本地文件中。 请注意,此示例中使用的是 POST 请求。您可以使用任何 HTTP 方法来发出文件下载请求,只要您在 API 控制器中使用相应的属性来接收文件名即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值