How to binary data to PDF file ASP.NET MVC

2.8k Views Asked by At

I develop a student information system.I inser the PDF file to the database as a binary for each course.I want users to download this file.Downloading file but not displaying.Where am I doing wrong.

MvcCode

  public FileResult FileDownload(Ders not)
    {
        byte[] byteArray = GetPdfFromDB(not.DersId);
        MemoryStream pdfStream = new MemoryStream();
        pdfStream.Write(byteArray, 0, byteArray.Length);
        pdfStream.Position = 0;
        //return new FileStreamResult(pdfStream, "application/pdf");
        return File(pdfStream, "application/pdf", "DersNot.pdf");

    }

     private byte[] GetPdfFromDB(int id)
    {
        #region
        byte[] bytes = { };
        using (SqlConnection con = new SqlConnection(@"Server=****;Database=***;UID=***;PWD=***"))
        {
            con.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "SELECT DersNotIcerik FROM Ders WHERE DersId=@Id";
                cmd.Parameters.AddWithValue("@Id", id);
                cmd.Connection = con;

                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    if (sdr.HasRows == true)
                    {
                        sdr.Read();
                        bytes = (byte[])sdr["DersNotIcerik"];
                    }
                }
                con.Close();
            }
        }

        return bytes;
        #endregion
    }

View

@Html.ActionLink(item2.DersNotAd, "FileDownload", new { id = item2.DersId })
1

There are 1 best solutions below

0
On

I solved the problem like this.We can close the subject

    public FileResult FileDownload(int id)
       {

        SqlConnection con = new SqlConnection(@"Server=10UR\MSSQLSERVERR;Database=UniversiteDB;UID=onur;PWD=1234");

        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = "SELECT DersNotIcerik FROM Ders WHERE DersId=@Id";
        cmd.Parameters.AddWithValue("@Id", id);
        byte[] binaryData = (byte[])cmd.ExecuteScalar();
        return File(binaryData, "application/octet-stream", "DersNot.pdf");

    }