如何通过ajax

时间:2015-09-09 17:46:07

标签: java jquery ajax xls vraptor

我正在通过Ajax和VRaptor直接下载xls,VRaptor让你的论文笔直,并提供下面的代码文件:

public Download geraExcel() {
 File arquivo = //generate file 
 return new FileDownload(file, "MyFile.xls", "application/vnd.ms-excel", true);
}

问题是在ajax的成功中接收到这个文件,我有一个代码可以做到这一点,并且它完美地适用于txt,问题是xls打开已损坏,我很长时间研究解决方案来解决,都没有成功,继续文件已损坏。如果有人知道另一种方式使它工作,我感谢你。 Ajax.success代码如下:

success: function(response, status, xhr) {
    // check for a filename
    var filename = "";
    var disposition = xhr.getResponseHeader('Content-Disposition');
    if (disposition && disposition.indexOf('attachment') !== -1) {
        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        var matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
    }

    var type = xhr.getResponseHeader('Content-Type');
    var blob = new Blob([response], { type: type });

    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
        window.navigator.msSaveBlob(blob, filename);
    } else {
        var URL = window.URL || window.webkitURL;
        var downloadUrl = URL.createObjectURL(blob);

        if (filename) {
            // use HTML5 a[download] attribute to specify filename
            var a = document.createElement("a");
            // safari doesn't support this yet
            if (typeof a.download === 'undefined') {                
                window.location = downloadUrl;
            } else {
                a.href = downloadUrl;
                a.download = filename;
                document.body.appendChild(a);
                a.click();

                //Here is the problem, the original is about 15k,  
                // but the download file is about 26K

            }
        } else {                    
            window.location = downloadUrl;
        }

        setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
    }
}

0 个答案:

没有答案