Javascript 从服务器下载文件的最佳方式是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10912164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:32:46  来源:igfitidea点击:

What is the best way to download file from server

javascriptasp.netwcf

提问by Arbejdsgl?de

I have interesting task which requires me to download a dynamically generated file from a server (ASP.NET) to the client. On the client side it is just JavaScript (jQuery) and the client is able to generate a lot of parameters to customize how the data is exported.

我有一个有趣的任务,需要我从服务器 (ASP.NET) 将动态生成的文件下载到客户端。在客户端,它只是 JavaScript (jQuery),并且客户端能够生成大量参数来自定义数据的导出方式。

What is the best way to do download the file from the server? Should I use a WCF service such as what is described hereor simple page like this one?

从服务器下载文件的最佳方法是什么?我应该使用 WCF 服务,例如这里描述的内容还是像这样的简单页面?

I don't know how to download a file without reloading the page (I'm not sure that $.ajax will work in this case). Could someone please give me some direction on this topic? Thanks.

我不知道如何在不重新加载页面的情况下下载文件(我不确定 $.ajax 在这种情况下是否有效)。有人可以就这个主题给我一些指导吗?谢谢。

回答by Aristos

First you can create the file from a handler .ashx

首先,您可以从处理程序创建文件 .ashx

Let say that you have the file for downloading at download.ashxand you have some parametres to pass from your javascript, eg download.ashx?p1=8827&p2=8831to know what you going to create.

假设您有要下载的文件,download.ashx并且您有一些参数要从您的 javascript 传递,例如,download.ashx?p1=8827&p2=8831要知道您要创建什么。

Then on your javascript you simple can make a redirect as

然后在您的 javascript 上,您可以简单地进行重定向

window.location = "download.ashx?p1=8827&p2=8831";

or alternative you can use the window.openfor do the same think

或者你可以使用window.openfor 做同样的想法

window.open("download.ashx?p1=8827&p2=8831");

and your file will start the download.

您的文件将开始下载。

Just make sure that you have set the header of attachment, and the correct contenttype on your handle eg:

只需确保您已设置附件标题,以及句柄上的正确内容类型,例如:

  HttpContext.Current.Response.ContentType = "application/octet-stream";
  HttpContext.Current.Response.AddHeader("Content-Disposition", 
                    "attachment; filename=" + SaveAsThisFileName);

Simple and clear, both tested and working.

简单明了,经过测试和工作。

Also you may interesting on this answer: How to handle errors.

您也可能对这个答案感兴趣:如何处理错误