在VueJS中下载空pdf



我下载了pdf文件,但它是空的。当我打开它,我得到这个

加载PDF文档失败。

这是我的BE:

[HttpGet("{id}/contract-agreement")]
[Produces("text/html", "application/pdf", Type = typeof(FileContentResult))]
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ValidationErrorResponse))]
[ProducesResponseType(StatusCodes.Status401Unauthorized, Type = typeof(ValidationErrorResponse))]
[ProducesResponseType(StatusCodes.Status404NotFound, Type = typeof(ValidationErrorResponse))]
public async Task<FileContentResult> GetContractAgreementAsync([FromRoute] string id, GetOverdraftContractAgreementRequest request)
{
var query = new GetOverdraftContractAgreementQuery(
id,
request.ContentType.ToMimeContentType());
var result = await Mediator.Send(query);
return File(result.Content, result.MimeContentType);
}
这是我的VueJS模板:
<template>
<div class="overdraft-documents-wrapper">
<b-button-group>
<div v-if="documents.contract">
<button @click="exportFile(documents.overdraftId, 'contract.pdf')" class="btn btn-info documents-btn mr-3">Download Contract</button>
</div>
<div v-if="documents.sef">
<button @click="exportFile(documents.overdraftId, 'sef.pdf')" class="btn btn-info documents-btn">Download SEF</button>
</div>
</b-button-group>
</div>
</template>

这些是我的方法:

async exportFile (document, fileName) {
if (fileName === 'contract.pdf') {
this.mergeFilters(document)
await this.fetchContractAgreement({ id: document, filters: this.filters }).then(response => {
console.log(response)
this.downloadFile2(response, fileName)
})

downloadFile2 (res, fileName) {
const fileURL = `data:application/pdf;,${res}`
const fileLink = document.createElement('a')
fileLink.href = fileURL
fileLink.setAttribute('download', fileName)
document.body.appendChild(fileLink)
fileLink.click()
},

请帮助。我不明白哪里出错了。我花了两天时间在这件事上。

当我在postman中调用这个端点时,它成功返回PDF。

在Vuejs模板中,你必须在axios调用中定义responseType,试试这个

axios({
url: "",
method: "GET",
responseType: "blob", // important
}).then((response) => {});

响应类型blob在处理pdf/images等文件时非常重要。

最新更新