Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

javascript - What is the best way to download file from server

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.

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

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First you can create the file from a handler .ashx

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

Then on your javascript you simple can make a redirect as

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

or alternative you can use the window.open for do the same think

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...