文件流下载本地

75 阅读1分钟
var DownloadUpload=(function () {
    return {
        parameterSplicing(api,params={}){//参数拼接
            let index=0;
            for(let key in params){
                if( params[key]){
                    if(index==0){
                        //首个参数不需要&
                        api +='?'+ key + '=' + params[key]
                    }else{
                        api += '&' + key + '=' + params[key]
                    }
                    index++;
                }
            }
            return api;
        },
        downloadByHref(api,params={}){
            let downLoadUrl=DownloadUpload.parameterSplicing(api,params);
            window.location.href = downLoadUrl;
        },
        downloadFileByUrl (url,filename){ //通过a标签和url去下载文件
            let aElement = document.createElement('a');
            aElement.href = url;
            aElement.download = filename;
            aElement.style.display = 'none';
            document.body.appendChild(aElement);
            aElement.click();
            document.body.removeChild(aElement);
       },
        downloadFileByFetch (api,params={},options={}){ //通过接口请求去下载文件,该方法可以监听load
            return new Promise((resolve, reject)=>{
                let {filename,isLoading=true}=options;
                let loadingInstance ;
                if(isLoading===true){
                    const {ElLoading } = ElementPlus;
                    loadingInstance  = ElLoading.service({
                        text:'下载中...'
                    })
                }
                let downLoadUrl=DownloadUpload.parameterSplicing(api,params);
                let defaultFileName='';
                fetch(downLoadUrl).then(response => {
                    let  contentDisposition=response.headers.get('Content-Disposition');
                    if (contentDisposition) {
                        defaultFileName =decodeURIComponent( contentDisposition.split('filename=')?.[1]);
                    }
                    return response.blob(); // 获取blob数据
                }).then(blob => {
                    const url = URL.createObjectURL(blob);
                    DownloadUpload.downloadFileByUrl(url, filename || defaultFileName);
                    window.URL.revokeObjectURL(url); // 释放URL对象
                    resolve()
                    if(isLoading===true){
                        loadingInstance.close()
                    }
                }).catch(err=>{
                    reject(err)
                    if(isLoading===true){
                        loadingInstance.close()
                    }
                })
            })
        }
    };
})();