【问题标题】:download blob file from sql using c# asp.net and present a save dialog to user使用 c# asp.net 从 sql 下载 blob 文件并向用户显示保存对话框
【发布时间】:2013-09-09 02:33:54
【问题描述】:

我已经在网上搜索了几个小时。尽管将 blob 文件上传到 sql 数据库似乎很容易,但再次尝试下载它是一场噩梦。

我有一个显示记录的网格视图。网格视图有一个链接按钮,我想用它来下载一个 blob 文件,该文件保存在与网格视图从中加载数据的位置相同的表中。我通过 onclick 事件将记录 id 传递给我的代码隐藏函数。

这是我的点击事件代码

protected void Downloadbutton_Click(Object sender, CommandEventArgs e)
    {

        string reqid = e.CommandArgument.ToString();

        using (SqlConnection connection = new SqlConnection("ConnectionString"))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "Select Attached_File_Name from ABSENCE_REQUEST where Request_ID = @Request_ID";
            cmd.Connection = connection;
            cmd.Parameters.AddWithValue("@Request_ID", Convert.ToInt32(20057));

            byte[] buffer = (byte[]) cmd.ExecuteScalar();
            using (FileStream fs = new FileStream(@"C:\test.pdf", FileMode.Create))
            {
                fs.Write(buffer, 0, buffer.Length);
            }
        }
    }

我知道在我的代码中我实际上设置了文件的下载位置。但是如何更改它,以便询问用户将文件保存在哪里?

【问题讨论】:

    标签: c# sql download save blob


    【解决方案1】:

    我认为您可以简单地将数据写入响应(未测试),例如:

    private void WriteFile (Byte[] bytes, string fileName)
    {
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = dt.Rows[0]["ContentType"].ToString();
        Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }
    

    您可能还想考虑为此创建一个通用处理程序,因此您的代码将非常相似,但是您可以拥有指向文件的链接,而不是仅在单击按钮时可用,例如您的链接可能是:

    YourWebsite/Downloads/RequestFileHandler.ashx?RequestID=5
    

    下载request_ID为5的文件

    编辑

    对不起,完全假设这是一个网页,但现在意识到它可能不是,在这种情况下你可以使用类似的东西:

    private bool SaveBytesToFile(byte[] butes)
    {
        var saveFileDialog = new SaveFileDialog();
        if (saveFileDialog.ShowDialog() != DialogResult.Cancel)
        {
            using (var fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
            {
                fileStream.Write(bytes, 0, bytes.Length);
            }
            return true;
        }
        return false;
    }
    

    【讨论】:

    • 我尝试了您提出的解决方案。我没有收到任何错误消息,但单击下载按钮后没有任何反应。我使用了一个断点并确保代码确实获取了 byte[] 数据并且确实如此。但是前端什么也没发生……有什么想法吗?
    • 是网页应用还是windows应用?
    • 它是一个 Web 应用程序(实际上是 SharePoint 的一个 Web 部件),但规则相同。我刚刚弄清楚为什么点击事件没有发生任何事情。该按钮位于 grdiview 内部,而 grdiview 位于 asp:updatepanel 内部。只是为了测试理论,我复制了一个按钮并将其放在页面上的更新面板之外。该按钮与您的解决方案完美配合。现在我有一个新问题......让该功能在更新面板中工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多