欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Web前端js下载流文件

程序员文章站 2022-04-13 15:25:27
前端下载文件大概有以下种: 1)a标签链接下载 2)表单form提交下载 3)使用XMLHttpRequest对象下载 ......

前端下载文件大概有以下种:

1)a标签链接下载

<a href="url">点击链接下载</a>

 

2)表单form提交下载

var form = $("<form></form>").attr("action", url).attr("method", "post");
        form.append($("<input></input>").attr("type", "hidden").attr("name", "参数1").attr("value", "值1"));
        form.append($("<input></input>").attr("type", "hidden").attr("name", "参数2").attr("value", "值2"));
        form.appendto('body').submit().remove();
//url为请求地址

 

3)使用xmlhttprequest对象下载

var xhr = new xmlhttprequest();            
        var formdata = new formdata();            
        formdata.append('参数1', "值1");            
        formdata.append('参数2',"值2");            
        xhr.open('post', url, true);           
        xhr.setrequestheader("token", token);     //可以带请求头   
        xhr.responsetype = 'blob'; 
        xhr.onload = function (e) {               
            if (this.status == 200) {                    
                var blob = this.response;
                //var responseheaders = xhr.getallresponseheaders();
                //var contentdisposition = this.getresponseheader("content-disposition");
                //var filename = this.getresponseheader("content-disposition").split('filename=')[1];  
// 获取文件名,需要在后端响应头暴露("access-control-expose-headers", "content-disposition");

var filename = "xxxx.xxx"; if (window.navigator.mssaveoropenblob) { navigator.mssaveblob(blob, filename); } else { blob.type = "application/octet-stream"; var url = url.createobjecturl(blob); var a = document.createelement('a'); a.href = url; a.download = filename; a.click(); window.url.revokeobjecturl(url); } }else if(this.status == 404){ alert("file does not exist!"); }else{ alert("failed to download file! "); } }; xhr.send(formdata);