在ASP.Net中使用SaveAs对话框实现下载

时间:2014-10-17 06:57:48

标签: asp.net

我正在尝试显示一个PopUp来保存文件,用户必须选择目标并更改文件类型(如果他确实需要)。我读过许多文章,因为我刚接触.Net,所以仍然没有清楚知道该怎么做。    这是代码。当我运行代码并单击网格视图中的链接按钮时,文件将在没有弹出的情况下下载,甚至不需要用户的许可,必须保存下载的文件

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if(e.CommandName == "Download")
        {
            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("content-disposition","attachment; filename=" + e.CommandArgument);
            Response.TransmitFile(Server.MapPath("~/UploadedFiles/") + e.CommandArgument);
            Response.End();

        }

    }

我需要实现以下目标。

  • 显示“另存为文件”对话框

  • 文件类型应自动显示在SaveAs对话框中。例如,如果文件类型为图像,则在SaveAs对话框中应自动显示.jpg。 我在这里附上了我的输出图像 enter image description here 我对这个概念并不十分清楚。请提前帮助谢谢

2 个答案:

答案 0 :(得分:0)

SaveFileDialog是一个Windows窗体控件,它不适用于网站。

当服务器向其发送默认无法处理的流时,浏览器将显示“您要对此文件做什么”对话框 - 遗憾的是,大多数浏览器都可以处理文本流,因此只显示它们用户。

但是这样的事情会让你前进:

// Clear the response buffer:
   Response.Clear();

   // Set the output to plain text:
    Response.ContentType = "application/octet-stream";

   // Send the contents of the textbox to the output stream:
   Response.Write(txtNewFile.Text);

   // End the response so we don't get anything else sent (page furniture etc):
   Response.End();

答案 1 :(得分:0)

为了拯救你们所有人(以及我未来的自我),在各处寻找几乎每一张表格上的可怕答案都是为了拯救你们。这是一个小的ASP.NET/C#代码段,它会提示用户使用“保存/打开”对话框下载文件。

String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();

有关更多内容类型,请检查

http://en.wikipedia.org/wiki/Internet_media_type#List_of_common_media_types

相关问题