zoukankan      html  css  js  c++  java
  • 使用 javascript API -- fetch 实现文件下载功能

    在fetch中第一个为请求地址,第二个可以设置请求类型POST,GET,DELETE,UPDATE,PATCH和PUT,随后可以使用then来接收参数,因为异步操作第一个then标明请求类型,第二个then中可以拿到正确的返回值,catch显示返回错误信息。

    fetch('https://XXX', { method: 'POST', body: JSON.stringify({ username: 'admin', password: '*****' }), headers: { 'Content-Type': 'application/json;charset=utf-8' } }).then(response => response.json()).then(data => console.log(data)).catch(err => console.log(err)); fetch("https://api.github.com/users") .then((res) => { return res.json(); console.log(res) }) .then(data => { console.log(data); }) .catch(err => console.log(err));

    下载写法
         fetch(url).then(async res => await res.blob()).then(
                (blob) => {
                    console.log(blob);
                    // 创建隐藏的可下载链接
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = URL.createObjectURL(blob);
                    // 保存下来的文件名
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    // 移除元素
                    document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
                }
            )
     
  • 相关阅读:
    vue实现语音播报功能
    vue使用vueCropper裁剪功能,代码复制直接使用
    阿里云服务器安装mongodb并且启动
    脚手架安装react
    PHP 和Apache的安装和配置
    CentOS yum 源的配置与使用
    Linux -Yum 命令详解
    (干货)Linux学习资源推荐
    linux学习书籍推荐linux学习书籍推荐
    一些C++内容的总结(2013.10.17)
  • 原文地址:https://www.cnblogs.com/kyooo/p/13608006.html
Copyright © 2011-2022 走看看