首页 > 解决方案 > 在 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()
},

请帮忙。我不明白似乎是什么错误。我在这上面花了 2 天时间。

当我在邮递员中调用此端点时,它成功返回 PDF。

标签: c#vue.jspdf

解决方案


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

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

检查以供参考


推荐阅读