Sha*_*awn 6 javascript c# ajax jquery xmlhttprequest
所以我遇到了这个奇怪的问题,我试图显示从我的网络 API 收到的 pdf,但 pdf 在 Chrome 的新浏览器选项卡中显示为空白(IE 没有显示任何内容,但它 console.logs ajax 成功打回来)。
API 将其发送回我的 ajax 请求,如下所示:
public async Task<HttpResponseMessage> GetPdf(PdfModel model)
{
var pdf = await _pdfManager.GetPdfAsync(model);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(pdf);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "MyPdf.pdf";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
Run Code Online (Sandbox Code Playgroud)
这是调用另一个 API 来获取 pdf 的 GetPdfAsync 方法。当我使用 Postman 调用具有相同模型的 api 时,我确实得到了一个作为响应显示的 PDF,所以我知道效果很好。
public async Task<byte[]> GetPdfAsync(PdfModel, CancellationToken ct = new CancellationToken())
{
using (var client = new HttpClient())
{
client.BaseAddress = PdfGeneratorApiUrl;
var content = JsonConvert.SerializeObject(model);
const string endpoint = "myPdf/pdf";
var response = await client.PostAsync(endpoint, new StringContent(content, Encoding.UTF8, "application/json"), ct);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsByteArrayAsync();
}
else
{
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的ajax调用中,这就是我尝试显示它的方式,但是当我在新选项卡中打开pdf时,它显示一个空白pdf,其文件名是我在ajax成功中给它的。虽然在console.log中blob.size = 1053248。
$.ajax({
url: '/n/api/getPdf',
type: 'POST',
contentType: 'application/json',
responseType: 'arraybuffer',
data: JSON.stringify(getPdfRequest),
success: function (data) {
var blob = new Blob([data]);
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="MyPdf.pdf";
link.click();
},
error: function (data) {
console.log(data);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1739 次 |
| 最近记录: |