fetch实现网络资源(图片/视频/音频)的下载

2021-01-03  本文已影响0人  small_zeo

前言

前端用fetch实现网络资源的下载,例如excel,图片,视频,音频。
Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。

下载文件资源,对象为一个二进制数据流

fetch('http://example.com/movies.mp4').then(function(response) {
    response.arrayBuffer().then(res=> {
        let type = "video/*"  // 资源类型
        /* 常见资源类型
          1.excel: type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          2.图片: type = "image/*"
          3.视频: type = "video/*"
          4.音频: type = "audio/*"
        */
        let blob = new Blob([res], {type: type});
        // 获取的blob根据实际业务场景应用下载,或转化成其他格式的资源
         /* var objectUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        a.href = objectUrl;
        a.click();
        document.body.removeChild(a);
        */
     })
});

不管是请求还是响应都能够包含 body 对象。body 也可以是以下任意类型的实例。

image.png
上一篇下一篇

猜你喜欢

热点阅读