首页 文章

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

提问于
浏览
0

我试图显示一个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

    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();
    
  • 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

相关问题