简体   繁体   中英

Need help to change file format after the users download it from Database

Did I miss something in this code? cuz when I test it I get the file type as "File" not as PDF.

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString); 
    conn.Open();
    string pdffile = "select pdf from users where ID='" + TextBoxLic.Text + "'";
    SqlCommand pdfcom = new SqlCommand(pdffile, conn);
    SqlDataReader reader = pdfcom.ExecuteReader();
    if (reader.Read())
    {
        Byte[] pdfData = (byte[])reader.GetValue(0);
        Response.ContentType = "Application/pdf";            
        Response.AppendHeader("content-disposition", "attachment; filename=" + TextBoxLic.Text);
        Response.BinaryWrite(pdfData);
        Response.End();
        conn.Close();
    }
}

https://i.gyazo.com/8eb75d4e55bed17155690531841d80c7.png

Maybe try adding a

Response.Flush(); Response.Close();

after Response.BinaryWrite(pdfData);

More importantly it should be while (reader.Read()) rather than if (reader.Read())

I'd suggest you read up on here: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read(v=vs.110).aspx

您需要将Content-Type标头设置为application/pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM