首页 > 解决方案 > React + .net core api 中的下载文件问题

问题描述

我正在尝试在我的反应应用程序上实现文件下载,API 是一个 .net 核心 api。

我正在使用fileSaver js来实现前端,但它似乎没有正确保存文件。

我的 API:

        [Authorize]
        [HttpGet]
        public async Task<IActionResult> DownloadInvoice(string ID)
        {
            var invoiceContent = await this.getfile(ID); 
            //this returns a byte array of the PDF file content
            if (invoiceContent == null)
                return NotFound();
            var stream = new MemoryStream(invoiceContent); //saves it into a stream
            stream.Position = 0;
            return File(stream, "application/octec-stream", $"{invoiceNo}.pdf");
        }

我的反应代码:

    import { saveAs } from 'file-saver';
    axios
    .get(url, {
        headers: {
          'Content-Type': 'application/json',
          responseType: 'blob',
        },
      })
      .then(function(res) {
            var blob = new Blob([res.data], {
                  type: 'application/pdf',
                });

            saveAs(blob, invoice.invoiceNo + '.pdf');
        });
    }}

我用邮递员测试了API,它返回正确的数据,我可以正确保存文件,

结果在邮递员中看起来像这样,这是 PDF 文件的正确内容:

%PDF-1.6
%����
1 0 obj
<<
/Creator(Telerik Reporting 7.1.13.612 \(http://www.telerik.com/products/reporting.aspx\))
/Producer(Telerik Reporting 7.1.13.612 \(http://www.telerik.com/products/reporting.aspx\))
/CreationDate(D:20190124112008+13'00')
>>
endobj
2 0 obj
<<
/Type/Catalog
/ViewerPreferences 3 0 R
/Pages 4 0 R
>>
endobj
3 0 obj
[bla bla bla....]

但是当它在反应中通过blob保存时,它会创建一个带有空白页的“有效”pdf文件。文件大小增加(从 43k 到 76k)..

我想知道是否有人知道这个实现有什么问题,并能指出我正确的方向。

非常感谢

标签: reactjs.net-corefilesaver.js

解决方案


好的,问题是这样的:

 .get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        responseType: 'blob', ////move this line out of the headers....
      })

推荐阅读