ASP.NET Response.TransmitFile() 似乎不起作用
我正在用一段 JQuery 调用 [WebMethod]。以下代码的目的是将最近压缩的文件发送到用户的浏览器。当用户单击“下载”按钮时,AJAX 请求将发送到 ASP.NET 页面,并应发送 zip 文件。
这是代码。
[WebMethod]
public static void DownloadAlbum(string folderToDownload)
{
string archiveDir = "";
...some code...
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + path);
HttpContext.Current.Response.TransmitFile(path);
HttpContext.Current.Response.End();
}
运行时,不会向浏览器发送任何内容,但也不会引发异常。我不确定发生了什么以及为什么文件没有下载。
“路径”肯定具有正确的地址,并且当文件的地址被硬编码时,也会发生同样的情况。
任何帮助将不胜感激!
谢谢,
I am calling a [WebMethod] with a piece of JQuery. The aim of the following code it to sent a recently zipped file to the user's browser. When the user clicks the 'Download' button, an AJAX request is sent to the ASP.NET page with is supposed to send the zip file.
Here is the code.
[WebMethod]
public static void DownloadAlbum(string folderToDownload)
{
string archiveDir = "";
...some code...
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + path);
HttpContext.Current.Response.TransmitFile(path);
HttpContext.Current.Response.End();
}
When this runs, nothing is sent to the browser, but no exceptions are thrown either. I'm unsure as to what is going on and why the file is not downloading.
The 'path' DEFINATELY has the correct address, and when the address of the file is hard-code the same happens.
Any help would be greatly appreciated!
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我通过网络服务传输文件时,我通常会采取一些不同的做法。我不会假装这是唯一的方法,但它过去对我有用。
我更喜欢使用 HTTP GET 动词检索文档,如下所示:
请注意,此方法属于 .asmx 服务,并且不是静态的。
在 web.config 中,我为 HttpGet 启用服务 (Documents.asmx),如下所示:
通过像这样配置的服务,可以通过常规超链接(无需 AJAX)从应用程序相对 URL
~/ 调用该服务Documents.asmx/DownloadAlbum?folderToDownload=myfoldername
。请注意,为了降低 CSRF 攻击的风险,您应该避免在可以更新系统的服务上启用 HttpGet。如果我计划启用 GET 读取方法,我通常会将插入/更新/删除方法保留在单独的服务中。
When I transfer files via a web service, I usually do things a little differently. I'll not pretend this is the only way to do it, but it has worked for me in the past.
I prefer to retrieve documents using the HTTP GET verb, as follows:
Note that this method belongs to an .asmx service, and is not static.
In the web.config, I enable the service (Documents.asmx) for HttpGet as follows:
With the service configured like so, the service can be called via a regular hyperlink without AJAX, from the application-relative URL
~/Documents.asmx/DownloadAlbum?folderToDownload=myfoldername
.Note that, to reduce the risk of CSRF attacks, you should avoid enabling HttpGet on a service that can update your system. I generally keep insert/update/delete methods in a separate service if I plan to GET-enable read methods.