如何在ASP.net上显示另存为对话框

时间:2014-08-08 03:59:54

标签: c# asp.net

我是asp.net上的新手,我正在开发在线报告生成器,我想让客户选择他/她想要放置他/她的文件的位置,所以这是我的代码,但没有'似乎工作,它返回到我的ajax错误语句我的ConfigurationManager.AppSettings [" ExtractFolder"]等于" c:\ temp \":只是想问什么&#39 ;代码错了吗?

context.Response.ContentType = "application/vnd.ms-excel";            
context.Response.AddHeader("content-disposition", "attachment;filename="+filename);
context.Response.WriteFile(ConfigurationManager.AppSettings["ExtractFolder"]+filename);
context.Response.Flush();
context.Response.End();

3 个答案:

答案 0 :(得分:1)

试试这个

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/MIME_type#List_of_common_media_types

答案 1 :(得分:0)

首先,检查要发送给用户的源文件是否在c:\ temp \中,并且已将 filename 设置为要发送的文件的名称。接下来,您需要确保.net进程在您的服务器上具有c:\ temp的权限。它可能没有。

另外,请确保您了解 response.writefile 实际上是从服务器读取文件并将其写入浏览器。您无法指定用户将文件保存到本地的位置,这由浏览器处理,而不是由您的代码处理。

使用Coders示例代码确保更改以下内容(请参阅我的评论)

String FileName = "FileName.xlsx";   //MAKE SURE THIS IS YOUR EXCEL FILENAME ON YOUR SERVER
String FilePath = "C:/...."; //SET THIS TO THE FOLDER THE FILE IS IN (put your file in your root folder of your website for now, you can move it later once you get the download code working)
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //MAKE SURE YOU HAVE CHANGED THIS TOO
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();

我还建议先在独立页面中尝试上述内容,然后在知道其工作后将其合并到AJAX页面中。

答案 2 :(得分:0)

基本上你不能按照你想要的方式做你想做的事。

您拥有的ASP.net代码依赖于完整的http请求/响应周期。设置标题的部分是告诉浏览器下载内容的部分。

AJAX请求正在寻找带有请求的特定返回,通常是javascript可通过的数据。你没有返回这个,而是文件的内容。

这是一个article,它解释了概念和问题。它还为您提供了另一种解决方案。基本上,该解决方案围绕使用iFrame来处理文件下载请求。