提示用户在ASP.NET C中保存/打开文件#

不应该很难找到如何做到这一点。 基本上我正在尝试取一个字符串,让客户端点击按钮时保存它。 它应该弹出一个Save / Open对话框。 没有额外的花里胡哨或任何东西。 这不是火箭科学,(或者我认为)。

似乎有很多不同的方式,(StreamWriter,HttpResponse等),但我找不到任何能够正常工作或解释正在发生的事情的例子。 提前致谢。

我找到的众多代码块中的一个例子……

(这只是一个例子,请不要以此为基础做出答案。)

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

第2行说要替换那个字符串。 怎么样? 这段代码被宣传为提出一个对话框。 我不应该在代码中设置路径,对吧?

编辑:最终结果(再次编辑,删除必须在结束前();)

  string FilePath = Server.MapPath("~/Temp/"); string FileName = "test.txt"; // Creates the file on server File.WriteAllText(FilePath + FileName, "hello"); // Prompts user to save file 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 + FileName); response.Flush(); // Deletes the file on server File.Delete(FilePath + FileName); response.End(); 

第2行(FilePath)表示服务器上文件的路径

第8行:

 response.TransmitFile(FilePath); 

将特定文件传输到客户端,然后弹出保存对话框。

如果您不传输文件,我不确定是否会弹出对话框(即使您设置了标题)

无论如何,我认为第8行应该是:

  response.TransmitFile(FilePath + FileName); 

浏览器会出现一个默认对话框,如果它会将Response视为某个文件。 如果您希望浏览器显示该默认对话框,您需要做的就是将响应作为文件发送到浏览器,您可以通过以下多种方式执行此操作:

  1. 如果是静态文件,

    • 最好的方法是在锚标记的href中提及文件的路径(显然,如果你没有安全问题)
    • 刚刚与您的回复一起,就像您在示例中所做的那样。
    • 其他方式你可以在这里参考4种方式从asp.net发送pdf
  2. 如果它是您需要在运行时生成的动态文件,您可以执行一个技巧,从文件流生成文件,将其放在服务器的某个临时文件夹中,如上所述将其作为静态文件读回。

FilePath应该指向您要发送给客户端的文件。 这是服务器上的路径。

只需使用此代码,它应该工作,以提示用户打开一个对话框,打开或保存系统上的文件….

 byte[] bytesPDF = System.IO.File.ReadAllBytes(@"C:\sample.pdf"); if (bytesPDF != null) { Response.AddHeader("content-disposition", "attachment;filename= DownloadSample.pdf"); Response.ContentType = "application/octectstream"; Response.BinaryWrite(bytesPDF); Response.End(); }