Ajax请求下载文件

来源:互联网 发布:js调用手机相册插件 编辑:程序博客网 时间:2024/04/30 23:23

以前我这样做,现在感觉很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, true, document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, 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.";    }});
0 0
原创粉丝点击