2016-11-04 114 views
2

enter image description here請幫忙。它顯示「無法加載PDF文檔」無法加載PDF文檔(MVC)

我沒有找到我在代碼中犯的錯誤。

這是我的代碼:

查看:

<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; } 
+0

您能否發佈您的錯誤消息? –

+0

這是一個有效的PDF字節在這裏返回,'byte [] contents =(byte [])content.Result;'? – Aruna

+0

@Aruna,是的,它是有效的。 –

回答

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"); 
} 
+0

嗨,謝謝你的迴應。仍然收到錯誤:「無法加載PDF文檔」。 –

+0

然後你的字節數組可能有損壞的數據。 – Nkosi

+0

在其他瀏覽器中嘗試一下,以確保它不是瀏覽器特定的。 – Nkosi

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"); 
} 
+0

您好,我收到以下錯誤:不能隱式地將類型'System.Web.Mvc.RedirectToRouteResult'轉換爲'System.Web.Mvc.FileContentResult'。 –

+0

嘗試返回類型爲「ActionResult」。我編輯了上面的代碼。 – Aruna

+0

感謝您的回覆。我得到這個錯誤:本地主機頁面不起作用 本地主機發送無效響應。 ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION –