Glydel Gorospe Glydel Gorospe - 1 month ago 15
C# Question

Failed to load PDF document (MVC)

enter image description herePlease help. It shows "Failed to load PDF document".

I didn't find where I mistake in code.

This is my code:

View:

<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>


Controller:

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


Model:

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

Answer

Given that content.Result is already a byte array of the pdf then just return the byte array.

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