Ajax请求下载文件

之前我这样作,如今感受很low:web

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

如今能够这样作,直接上代码,我这里贴的是AngularJS的HTTP请求函数,ajax也是相似的: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.";
    }
});
相关文章
相关标签/搜索