How can I download a PDF file from a registry in a MySQL database with C #?

0

With the help of this query, ( How can I attach a PDF file to a DB record in SQL with C #? ) and  with some small modifications I was able to add a PDF file to a MySQL table, now I have the inverse problem, this is I need to be able to download the loaded file, I am using VS2015, beforehand thanks ....

    
asked by Alberto Maureira 08.04.2016 в 00:27
source

2 answers

0

In the previous question in the article that I suggest I explain how to download a file

[ASP.NET] Burn file on base of data

If you analyze the data layer you will see the method to recover a file by the id.

    public static byte[] GetById(int Id)
    {
        using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()))
        {
            conn.Open();

            string query = @"SELECT archivo
                            FROM Archivos
                            WHERE Id = @id";

            MySqlCommand cmd = new MySqlCommand(query, conn);
            cmd.Parameters.AddWithValue("@id", Id);

            MySqlDataReader reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                return (byte[])reader["archivo"];
            }

        }

        return null;

    }

The important thing is to see how the content of the field is assigned as byte[] in the line of the return

With that result you should send it in Response to the client for download. There are several ways to achieve the download but the simplest is through a page that could be called download.aspx

public partial class Download : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(Request.QueryString["id"]);

        byte[] archivo = ArchivosDAL.GetById(id);

        Response.Clear();

        Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", "nombrearch.pdf"));
        Response.ContentType = "application/octet-stream";

        Response.BinaryWrite(archivo.ContenidoArchivo);
        Response.End();

    }
}

The ContentType = "application/octet-stream" is defined to show the download box instead of showing the pdf embedded in the browser

    
answered by 08.04.2016 / 01:58
source
0

The code of the league that you expose, saves in the DB the PDF in Base64, now you must do the opposite to decode the Base64 to physical file, and that you do it in the following way.

Assuming you already have in a variable the base64 of the PDF obtained through a query or something similar, example b64Str

You convert it to file as follows

Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
    
answered by 08.04.2016 в 01:12