我已经创建了一个下载链接。但是下载的文件缺少文件类型(每次都会下载一个纯文件)

时间:2019-04-02 03:01:05

标签: c# hyperlink download

protected void downloadbtn(object sender, EventArgs e)
{
    int id = int.Parse((sender as LinkButton).CommandArgument);
    byte[] bytes;
    string fileName, contentType;
    using (SqlConnection con = new SqlConnection(str))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select Name, Data, Type from demons where ID=@Id";
            cmd.Parameters.AddWithValue("@ID", id);
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                sdr.Read();
                bytes = (byte[])sdr["Data"];
                contentType = sdr["Type"].ToString();
                fileName = sdr["Name"].ToString();
            }
            con.Close();
        }
    }
    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = contentType;
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}

//文件类型不随文件一起发送 //例如,如果要下载照片,则将下载一个普通文件,然后您需要使用paint或photos应用专门打开它

1 个答案:

答案 0 :(得分:0)

我相信您的问题是,contentType变量中存储的内容不是有效的MIME类型。

您可以在https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms775147(v=vs.85)

处查看已知的Windows MIME类型列表。