【问题标题】:file extensions lost between browsers in asp.net c# application在 asp.net c# 应用程序中的浏览器之间丢失文件扩展名
【发布时间】:2013-07-02 04:19:49
【问题描述】:

我有一个技术问题要问你们中的一些人。

基本上我主要在 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
            }
        }
    }

【问题讨论】:

  • 这个帖子似乎和你有同样的问题stackoverflow.com/questions/5198530/…
  • 您应该尝试设置ContentType,有时浏览器会忽略扩展名,而直接使用ContentType
  • filename=后面的\"应该去掉,或者在dr["Filename"].ToString()之后关闭
  • 问题已解决,感谢您的意见

标签: c# asp.net sql sql-server


【解决方案1】:

使用 F12 开发工具或 FireBug 或类似工具查看服务器实际发送的内容。在这种情况下,它将类似于:

Content-Disposition: attachment;filename="filename.ext

服务器也可以默认发送这个或类似的东西:

Content-Type: text/html

首先,您需要关闭文件名后的引号。还建议在分号后加一个空格。您还需要清理文件名以确保它不包含混淆或非法字符。至少你需要去掉双引号或引用它们。

其次,您需要添加一个 Content-Type 标头。秘籍是设置

Content-Type: application/octet-stream 

这将导致浏览器根据文件扩展名进行猜测。

【讨论】:

  • 是的,你认为它会保存为 html 文档是对的,它对除 office 文件之外的每个文件都执行此操作
  • 引号是我的罪魁祸首。谢谢!
【解决方案2】:

请再次检查文件名。如果文件下载有 1 个字符是空格键 (" ") 示例:“模板 import.xls”。 Firefox 在下载时会出现没有扩展的错误。您可以使用 replace(" ", "") 函数来解决此问题:

Response.AddHeader("Content-Disposition", "attachment;filename=\"" + replace(dr["Filename"].ToString(), " ", "");

【讨论】:

    猜你喜欢
    • 2016-08-27
    • 2014-06-08
    • 2013-05-08
    • 2021-12-30
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    相关资源
    最近更新 更多