繁体   English   中英

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

[英]How to show Save As Dialog on ASP.net

我是asp.net的新手,正在开发Online Report Generator,我想让客户端选择他/她想要放置文件的位置,所以这是我的代码,但似乎没有用,它返回到我的ajax错误语句,我的ConfigurationManager.AppSettings [“ ExtractFolder”]等于“ c:\\ temp \\”:只想问一下代码出了什么问题?

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

尝试这个

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

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

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

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

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页面中。

基本上,您无法按照自己想做的方式去做自己想做的事情。

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

AJAX请求正在寻找带有其请求的特定返回值,通常是JavaScript可传递的数据。 您没有返回这个,而是文件的内容。

这是一篇文章 ,对概念和问题进行了一些解释。 它还为您提供了替代解决方案。 基本上,解决方案围绕使用iFrame来处理文件下载请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM