asp.net c#应用程序中的文件扩展名在浏览器之间丢失
本文关键字:浏览器 之间 扩展名 文件 net 应用程序 asp | 更新日期: 2023-09-27 18:20:54
我有一个技术问题要问你们中的一些人。
基本上,我主要在firefox中测试我的应用程序,我在应用程序中有一个下载功能,用户可以从SQL server数据库下载文件。问题是,当我在Internet explorer中下载文件时,除了Microsoft文件外,每个文件都会失去扩展名,例如word、access等。除了位图,firefox中没有问题。。。
这是我的代码,谢谢
//Download attachment file
protected void AttachmentDLBut_Click(object sender, EventArgs e)
{
//set the ID for the selected row
var ID = Request.QueryString["Id"];
using (SqlConnection conn = new SqlConnection("******"))
{
string sql = "SELECT FileType, Filename, Description FROM NetworkEquipment WHERE NetworkEquipmentID = '" + ID + "'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
//cmd.Parameters.AddWithValue("@ID", AttachmentDDL.SelectedItem.Value);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
try
{
//if there is an attachment... download it
if (dr.Read())
{
Response.Clear();
Response.ContentType = dr["FileType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename='"" + dr["Filename"].ToString());
Response.BinaryWrite((byte[])dr["Description"]);
Response.End();
conn.Close();
}
}
catch (SqlException sqlex) { MessageBox.Show("Sorry, an unexpected error has occurred while downloading this file. Error: " + sqlex); }
catch (Exception ex) { MessageBox.Show("Sorry, an unexpected error has occurred while downloading this file. Error: " + ex); }
//else nothing happens
}
}
}
使用F12开发工具或FireBug或类似工具查看服务器实际发送的内容。在这种情况下,它将类似于:
Content-Disposition: attachment;filename="filename.ext
默认情况下,服务器也可以发送此消息或类似消息:
Content-Type: text/html
首先,您需要关闭文件名后的引号。还建议在分号后面加一个空格。您还需要清理文件名,以确保它不包含混淆或非法的字符。至少你需要去掉双引号或引用它们。
其次,您需要添加一个Content-Type标头。作弊是设置
Content-Type: application/octet-stream
这将导致浏览器基于文件扩展名进行猜测。
请再次检查文件名。如果文件下载有1个字符是空格键(")示例:"templateimport.xls"。Firefox在下载时会出现没有扩展名的错误。您可以使用replace(",")来修复此问题:
Response.AddHeader("Content Disposition","attachment;filename=''"+replace(dr["filename"].ToString(),",");