无法加载PDF文档(MVC)

时间:2016-11-04 04:01:23

标签: c# asp.net-mvc sql-server-2008

enter image description here请帮忙。它显示"无法加载PDF文档"

我没有找到我在代码中的错误。

这是我的代码:

查看:

<a data-toggle="tooltip" data-placement="top" title="View" href="@Url.Action("DownloadFile", new { id = pat.ID })" target="_blank" class=" btn btn-success btn-sm">
<span class="glyphicon glyphicon-file" aria-hidden="true"></span></a>

控制器:

public FileStreamResult DownloadFile(int id)
{
    MemoryStream workStream = new MemoryStream();
    DataModel DB = new DataModel();
    /var content = DB._PATIENT.Where(m => m.ID == id).FirstOrDefault();
    byte[] contents = (byte[])content.Result;
    workStream.Write(contents, 0, contents.Length);
    workStream.Position = 0;

    Response.AddHeader("Content-Disposition", "inline; filename=someFile.pdf");
    return new FileStreamResult(workStream, "application/pdf");    
}

型号:

public int ID { get; set; }
public string PatientCode { get; set; }
public string CaseNo { get; set; }
public DateTime DatePerformed { get; set; }
public byte[] Result { get; set; }
public DateTime ExpirationDate { get; set; }
public string LaboratoryName { get; set; }

2 个答案:

答案 0 :(得分:0)

您可以返回FileContentResult而不是FileStreamResult,如下所示,

public ActionResult DownloadFile(int id)
 {
  MemoryStream workStream = new MemoryStream();
  DataModel DB = new DataModel();
  var content = DB._PATIENT.Where(m => m.ID == id).FirstOrDefault();
  byte[] contents = (byte[])content.Result;
  workStream.Write(contents, 0, contents.Length);
  workStream.Position = 0;

  Response.AddHeader("Content-Disposition", "inline; filename=someFile.pdf");
  return File(workStream, "application/pdf", "someFile.pdf");
}

答案 1 :(得分:0)

鉴于content.Result已经是pdf的字节数组,那么只返回字节数组。

public ActionResult DownloadFile(int id) {
    var DB = new DataModel();
    var patient = DB._PATIENT.Where(m => m.ID == id).FirstOrDefault();
    if (patient != null && patient.Result != null && patient.Result.Length > 0) {
        var content = patient.Result; //this is a byte[] of the pdf
        Response.AddHeader("Content-Disposition", "inline; filename=someFile.pdf");
        return File(content, "application/pdf");
    }
    return RedirectToAction("BadPatientFile");
}