【发布时间】:2017-08-02 07:54:10
【问题描述】:
我的 .NET Core 服务器上有一个 PDF,我需要以某种方式将其作为 BLOB 通过网络发送,以便我的 JS AJAX 请求可以将其转换回 PDF,以便下载。
间接的原因是因为文件来自我的API,只能通过AJAX访问。由于需要不记名令牌,我不能只在幕后使用表单,因为创建的站点没有 cookie。 (很奇怪,我知道,但目前就是这样,我不打算改变那部分)
所以,在我的 C# 方面,我尝试了几种变体,如下所示。 ApiResponse 只是我使用的一个容器,其中包含一个 bool 和一个 string(名为 message),因此我可以判断请求是否正确。
这些都是我一直在尝试的
return new ApiResponse(true, File.ReadAllText(path));
return new ApiResponse(true, Convert.ToBase64String(File.ReadAllBytes(path)));
return new ApiResponse(true, JsonConvert.SerializeObject(File.ReadAllBytes(path)));
在 JS 方面,以相同的顺序解析它,我有:
// Get the response in object form, since it's sent as an ApiResponse
const response = JSON.parse(xmlhttp.response);
const text = response.message;
const text = atob(response.message)
const text = JSON.parse(response.message)
我也尝试过
const text = atob(JSON.parse(response.message))
然后,我正在这样做:
const blob = new Blob([text], {type: "application/pdf"});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "file.pdf";
document.body.appendChild(a);
a.click();
这确实会正确生成已下载的文件。但是,该文件无效:它已损坏。
我几乎被困在这一点上,而且我无法找到使用这种方法从头到尾使用 Javascript 下载文件的东西。它要么是背面,要么是正面,但从不系在一起。
那么,我怎样才能成功地通过网络发送 PDF BLOB,并在前端重新创建它以便下载?
【问题讨论】:
标签: javascript c# ajax download blob