如何解决将 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 举报,一经查实,本站将立刻删除。