【问题标题】:How to download and save a pdf file from ASP.NET Core API from database in Angular?如何从 Angular 数据库中的 ASP.NET Core API 下载和保存 pdf 文件?
【发布时间】:2020-01-28 23:59:44
【问题描述】:

我的 Angular 项目无法通过 ASP.NET 核心 Api 下载(另存为)pdf 文件。 pdf文件存储在SQL server中。

我尝试了许多在 stackoverflow 中发布的方法,但没有一个适合我。一些示例下载了一个 pdf 文件,但如果尝试打开它,则会发现错误“..not support...damaged”。

API(我更喜欢只返回一行而不是单个 vaule byte[])

[HttpGet]
        [Route("detail/{studentid:int}/{reportSeq:int}")]
        public async Task<ActionResult<byte[]>> GetStudentAcademicReport2(int StudentID, int ReportSeq)
        {            
            var report = await _context.AcademicReportDetails.FromSql("select * from [dbo].[ufnStudentAcademicReport] (8213, 8158)").FirstOrDefaultAsync();
            if (report == null)
            {
                return NotFound();
            }
            return report.ReportContent;
        }
  1. 不适用于 Angular

this.httpClient.get("https://localhost:44369/api/values/detail/8213/8158", { responseType: 'blob'})
. 订阅(响应 => { 控制台日志(响应);

  const url = window.URL.createObjectURL(new Blob([response]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'file.pdf');
  document.body.appendChild(link);
  link.click();
  1. 不在安古拉工作

    this.httpClient.get("http://localhost:5000/api/studentacademicreports/detail/8213/8158", { responseType: 'arraybuffer'})
    . 订阅(响应 => { 控制台日志(响应);

      const file = new Blob([response], {type: 'application/pdf'});
      const fileURL = window.URL.createObjectURL(file);
    
      let objectURL = 'data:image/jpeg;base64,' +  response;
      let fileURL2 = this.sanitizer.bypassSecurityTrustUrl(objectURL); 
    
      const link = document.createElement('a');
      link.href = fileURL;
      link.download = 'sample.pdf';
      link.click();
    
  2. 在 Windows 窗体项目中工作

    cmd.CommandText = "从 [dbo].[ufnStudentAcademicReport] (8213, 8158) 中选择 *"; cmd.CommandType = CommandType.Text;

                    if (cmd.Connection.State != ConnectionState.Open)
                    {
                        cmd.Connection.Open();
                    }
    
                    DbDataReader read = cmd.ExecuteReader();
                    if (read.HasRows)
                    {
                        while (read.Read())
                        {
                            byte[] b = null;                                
                            b = (byte[])read.GetValue(read.GetOrdinal("ReportContent"));
                            System.IO.File.WriteAllBytes(@"c:\temp\test.pdf", b);    
                        }    
                    }
    
  3. 无法通过 API 在 Windows 窗体项目中工作

HttpClient http = new HttpClient(); var NewResponse = 等待 http.GetAsync("https://localhost:44369/api/values/detail/8213/8158");

        var content = await NewResponse.Content.ReadAsByteArrayAsync();

        System.IO.File.WriteAllBytes(@"c:\temp\test111.pdf", content);

从我上面的示例代码中可以看出,如果使用 SQLCommand 直接下载 varbinary(Max) 中的 pdf,则它可以工作,但如果通过 API 下载 pdf,则它不起作用。我怀疑 API 以 Json 格式返回 byte[]。学生照片通过 api 成功显示,没有任何问题,但下载 Pdf 文件不起作用。是什么导致下载的 PDF 文件在我的代码中损坏?

【问题讨论】:

    标签: arrays angular api pdf asp.net-core


    【解决方案1】:

    当您从 ASP.NET Core 操作返回 byte[] 时,它的结果是 base64 编码的,这就是您得到“损坏”文件的原因。您必须从操作中返回 FileResult 才能让框架正确处理二进制数据

    public async Task<FileResult> GetStudentAcademicReport2(int StudentID, int ReportSeq)
    {
        var report = await _context.AcademicReportDetails.FromSql("select * from [dbo].[ufnStudentAcademicReport] (8213, 8158)").FirstOrDefaultAsync();
        if (report == null)
        {
            return NotFound();
        }
        return File(report.ReportContent, "application/pdf", "test.pdf");
    }
    

    【讨论】:

    • 谢谢。最后它现在可以工作了。你节省了我几天的时间。根据您的想法,我对 base64 进行了一些研究,并点击了链接 link。现在它可以在您的方法中使用,也可以在 API 中使用正常的 byte[] 格式。
    • @Aussie 考虑一下。如果有帮助,请考虑接受答案。
    • 我愿意接受你的回答,但因为我的声誉,我似乎没有选择这样做。
    • @Aussie 查看左侧的灰色复选标记,位于答案的赞成/反对票下方。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2018-02-08
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多