简体   繁体   English

使用 AJAX 下载的文件未打开

[英]File downloaded with AJAX not opening

I have an issue with downloading a file with Ajax request, the file downloads successfully but it can't be opened.我在使用 Ajax 请求下载文件时遇到问题,文件下载成功但无法打开。 I don't know what I am missing.我不知道我错过了什么。 Your help is appreciated with the details given below.感谢您提供以下详细信息的帮助。

Thank you.谢谢你。

I have a JSP page with list of attachments, each with a Download button.我有一个带有附件列表的 JSP 页面,每个页面都有一个下载按钮。

When clicked on Download it calls the function named downloadFile( url )单击下载时,它会调用名为downloadFile( url )的 function

在此处输入图像描述

The code on download button下载按钮上的代码

<button onclick= "downloadFile('ProcessControllerHelper?action=download&attachmentId=<%=attachment.getAttachmentId() %>')" class="btn btn-sm btn-round btn-default"><bean:message key="lbl.download"/></button>

The function downloadFile that executes on download button下载按钮上执行的 function下载文件

function downloadFile( url )
    {
        $.ajax({
            type: "GET",
            url: url,
            headers: {
                'Content-Type': 'application/octet-stream'
            },
            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.href = downloadUrl;
                        } else 
                        {
                            a.href = downloadUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                        }
                    } else {
                        window.location.href = downloadUrl;
                    }
        
                    setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
                }
            }, error: function(error) {
                alert('<bean:message key="attachment.not.found" />');   
            }
        });
        
    }

When clicked on download button it downloads the files successfully, which can't be opened like in the screenshot at last.单击下载按钮时,它会成功下载文件,最后无法像屏幕截图中那样打开文件。

在此处输入图像描述

The issue is that the file downloaded is not being opened, and the error is something like we don't support the format问题是下载的文件没有打开,错误是我们不支持格式

在此处输入图像描述

Appreciate your help!感谢你的帮助!

I used the below function from the api ( http://danml.com/js/download2.js ), and it worked fine for me.我使用了 api ( http://danml.com/js/download2.js ) 中的 function ,对我来说效果很好。

function downloadFile( url )
    {
        var flag = 1;
        fetch(url, {
            method: "GET",
            headers: {
                    "Content-Type": "application/json; charset=utf-8"
                }
            })
            .then(response => {
                if (response.status === 200) {
                    filename = response.headers.get("content-disposition").split(";")[1].split('"')[1];
                    return response.blob();
                } else {
                    alert('Attachment not found!');
                    flag = 0;
                    return;
                }
            })
            .then(body => {
                if(flag > 0 ) {
                    download(body, filename, "application/octet-stream");
                }
            });
    
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM