将 Zip 文件下载为 Blob

问题描述

我正在创建一个 zip 文件,并尝试通过对 aspx 页面后面代码中定义的函数的 ajax 调用来下载它。我遇到的问题是我得到了 SyntaxError: Unexpected token P in JSON at position 0,我怀疑这是因为认情况下返回类型是 json。当 ResponseFormat 只有 xml 和 JSON 时,我将如何将其更改为 blob。我尝试将函数返回类型从字符串更改为对象,以使其无效。

[WebMethod]
public static string DownloadFiles(string files,string fileDirectory)
{
    createDirectory("my/images/personal/");
    createDirectory("my/Reports");
    createDirectory("my/Hello");

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.BufferOutput = false;
    HttpContext.Current.Response.ContentType = "application/zip";
    HttpContext.Current.response.addheader("content-disposition","attachment; MyZipFile.zip");

    using (ZipFile zip = new ZipFile())
    {
        try
        {
            zip.AddDirectory("my","MyZipFile");
            //zip.AddFile("ReadMe.txt");
            zip.Save(HttpContext.Current.Response.OutputStream);
        }catch (Exception ex)
        {
            //Log error here
        }
    }
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.End();

    return files + " " + fileDirectory;
}

Ajax 调用

$.ajax({
    type: "POST",url: "sub.aspx/DownloadFiles",data: JSON.stringify({ "files": "Hello","fileDirectory": "World" }),contentType: 'application/json; charset=utf-8',dataType: 'json',error: function (XMLHttpRequest,textStatus,errorThrown) {
        console.log(XMLHttpRequest);
        console.log("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },success: function (response) {
        console.log("--" + JSON.stringify(response));
    }
});

更新: 我已将 ajax 调用更改为使用 fetch api。我现在下载了文件,但它是空的

fetch("sub.aspx/DownloadFiles")
    .then(response => response.blob())
    .then(data => {
        let blobURL = URL.createObjectURL(data);
        let a = Object.assign(document.createElement('a'),{
            href: blobURL,download: "filename.zip"
        });
        document.body.appendChild(a);
        a.click();
        a.remove();
    });

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)