如何将二进制数据转换为PDF文件ASP.NET MVC

时间:2017-12-21 15:43:32

标签: c# asp.net-mvc pdf file-upload fileresult

我开发了一个学生信息系统。我将PDF文件作为每个课程的二进制文件输入数据库。我希望用户下载这个文件。下载文件但不显示。我在哪里做错了。

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
    }

查看

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

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我们可以关闭主题

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

    }