如何为上传的文件设置MIME类型?

时间:2015-07-07 15:54:01

标签: asp.net file-upload mime-types

我编写了这段代码,使用asp.net和C#将文件上传到数据库。 //此部分用于获取二进制数据和文件名以及MIME类型

string filename = Path.GetFileName(uploadcontract.FileName);
        if (filename != string.Empty)
        {
            String Conttype = uploadcontract.PostedFile.ContentType;
            Stream str = uploadcontract.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(str);
            Byte[] size = br.ReadBytes((int)str.Length);
            return size;
        }
        else
        {
           // do something
        }

使用名称和MIME类型成功保存数据库中的文件。我试图用这段代码下载相同的文件

 SqlCommand SelectCMD = new SqlCommand();
    sqlconn = new SqlConnection((String)ViewState["ConnStr"]);
    SelectCMD.CommandText = @"SELECT    tbl_Files_FileName,tbl_Files_FileContent,tbl_Files_FileMIME     FROM         tbl_Files            WHERE Seq=@sq";
    SelectCMD.Connection = sqlconn;
    SelectCMD.Parameters.AddWithValue("sq", Convert.ToInt64(Request.QueryString["ID"]));
    SelectCMD.CommandType = CommandType.Text;
    sda.SelectCommand = SelectCMD;
    int itemin = sda.Fill(ds, "downfile");
    sqlconn.Close();
    if (itemin != 0)
    {
            byte[] byt = (Byte[])ds.Tables["downfile"].Rows[0]["tbl_Files_FileContent"];
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = ds.Tables["downfile"].Rows[0]["tbl_Files_FileMIME"].ToString();
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + ds.Tables["downfile"].Rows[0]["tbl_Files_FileName"].ToString());
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.BinaryWrite(byt);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
    }

但我面临以下问题

Excel在“test.xlsx”中找到了不可读的内容。您要恢复此工作簿的内容吗?如果您信任此工作簿的来源,请单击“是”。

看起来文件类型有问题

0 个答案:

没有答案