加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax请求下载文件

发布时间:2020-12-16 01:29:06 所属栏目:百科 来源:网络整理
导读:以前我这样做,现在感觉很low: window .location .href = "http://127.0.0.1:8080/wx-sr-api/xxx/export" ; 现在可以这样做,直接上代码,我这里贴的是AngularJS的HTTP请求函数,ajax也是类似的: $http({ url: "http://127.0.0.1:8080/wx-sr-api/xxx/expor

以前我这样做,现在感觉很low:

window.location.href = "http://127.0.0.1:8080/wx-sr-api/xxx/export";

现在可以这样做,直接上代码,我这里贴的是AngularJS的HTTP请求函数,ajax也是类似的:

$http({
    url: "http://127.0.0.1:8080/wx-sr-api/xxx/export",method: 'GET',params: reqData,responseType: 'arraybuffer'
}).success(function (data,status,headers) {
    <!--var type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (!type)
        throw '无效类型';-->

    //对象 URL 也被称为 blob URL,指的是引用保存在 File 或 Blob 中数据的 URL。使用对象 URL 的
    //好处是可以不必把文件内容读取到 JavaScript 中而直接使用文件内容。为此,只要在需要文件内容的地
    //方提供对象 URL 即可。
    var urlCreator = window.URL || window.webkitURL;
    var blob = new Blob([data],{ type: type },decodeURI(headers()["x-filename"]));
    var url = urlCreator.createObjectURL(blob); //这个函数的返回值是一个字符串,指向一块内存的地址。

    //以下代码保存我的excel导出文件
    var link = document.createElement('a'); //创建事件对象
    link.setAttribute('href',url);
    link.setAttribute("download",filename);
    var event = document.createEvent("MouseEvents"); //初始化事件对象
    event.initMouseEvent("click",true,document.defaultView,0,false,null); //触发事件
    link.dispatchEvent(event);

}).error(function (data,status) {

});



//以下代码可以在页面中显示一个图像文件:
var filesList = document.getElementById("files-list");
EventUtil.addHandler(filesList,"change",function(event){
    var info = "",output = document.getElementById("output"),progress = document.getElementById("progress"),files = EventUtil.getTarget(event).files,reader = new FileReader(),url = createObjectURL(files[0]);
    if (url){
        if (/image/.test(files[0].type)){
            output.innerHTML = "<img src="" + url + "">";
        } else {
            output.innerHTML = "Not an image.";
        }
    } else {
    output.innerHTML = "Your browser doesn't support object URLs.";
    }
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读