我正在尝试使用 AJAX/JQuery 下载并保存 PDF 文件(我知道......)。
这是我在服务器端的内容:
public HttpResponseMessage GetPdf() {
var pdf = generatePdfByteArray(); // byte[]
var result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new ByteArrayContent(pdf);
//result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
//{
// FileName = "blah.pdf"
//};
// Tried with and without content disposition… Shouldn't matter, I think?
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
这是客户端:
let ajaxOptions = {
url: "/url",
type: "GET",
accepts: "application/pdf",
success: (data) => {
let blob = new Blob(data, {
type: "application/pdf",
}); // <-- this fails
// stuff...
},
};
$.ajax(ajaxOptions);
你知道这有什么问题吗?
第一个参数应该是序列。
因此,这是行不通的:
let blob = new Blob(data, {
type: "application/pdf"
});
但这会:
let blob = new Blob([data], {
type: "application/pdf"
});
这就是我最终的结果:
public HttpResponseMessage GetPdf()
{
var pdf = generatePdfByteArray();
var result = Request.CreateResponse(HttpStatusCode.OK);
var dataStream = new MemoryStream(pdf);
result.Content = new StreamContent(dataStream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "file.pdf"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}