zoukankan      html  css  js  c++  java
  • 跨域将blob对象保存到本地

    应用场景

    项目前后端分离,后端环境Django. 需要实现 前端可以下载后端生成的EXCEL文件同时对权限进行控制。

    将blob保存到本地

           function saveAs(blob,fileName) {
                if ('download' in document.createElement('a')) { // 不是IE浏览器
                    let url = window.URL.createObjectURL(blob)
                    let link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download', fileName)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link) // 下载完成移除元素
                    window.URL.revokeObjectURL(url) // 释放掉blob对象
                } else { // IE 10+
                    window.navigator.msSaveBlob(blob, fileName)
                }
            }

    获取blob内容,同样支持GETPOST获取

        var xmlhttp
        xmlhttp = new XMLHttpRequest()
        xmlhttp.onreadystatechange = function () { // Call a function when the state changes.
            if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
                // Request finished. Do processing here.
                console.log(xmlhttp.response)
                saveAs(xmlhttp.response, 'filename.xlsx')
            }
        }
        // async=false -同步,ture 异步
        xmlhttp.open(method='GET',url='http://ctcnc0378.carsgen.com:8000/budget/file_download?period_id=15', async=true)
        xmlhttp.setRequestHeader('Content-type', 'application/octet-stream')
        // 设置跨域访问的Token头
        xmlhttp.setRequestHeader('Authorization', 'Token 8002f4d3e770ada98ef5360c32e59d24f74b12cb')
        xmlhttp.withCredentials = true
        xmlhttp.responseType = "blob";
        xmlhttp.send(null)

    也可以用axios获取

    axios({
        method: 'post',
        url: 'api/user/',
        data: {
            period: '2021'
        },
        responseType: 'blob'
    }).then(response => {
        saveAs(response)
    }).catch((error) => {
    
    })
  • 相关阅读:
    zookeeper使用场景
    zookeeper安装配置
    hadoop 远程调试
    deep learning笔记
    Sentiment Analysis(1)-Dependency Tree-based Sentiment Classification using CRFs with Hidden Variables
    PRML阅读笔记 introduction
    Python 学习笔记(2)
    python nltk 学习笔记(5) Learning to Classify Text
    python nltk 学习笔记(4) Writing Structured Programs
    python nltk 学习笔记(3) processing raw text
  • 原文地址:https://www.cnblogs.com/Evan-fanfan/p/14876193.html
Copyright © 2011-2022 走看看