什么是从服务器下载文件的最佳方式 [英] What is the best way to download file from server

查看:133
本文介绍了什么是从服务器下载文件的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要从服务器(ASP.NET)到客户端下载一个动态生成的文件有趣的任务。在客户端,这只是的JavaScript(jQuery的)和客户机能够产生大量的参数来定制数据是如何导出。

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.

什么是做从服务器下载文件的最好方法?我应该使用WCF服务,如什么是描述<一个href=\"http://www.$c$cproject.com/Articles/166763/WCF-Streaming-Upload-Download-Files-Over-HTTP\">here或如这个?

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.

推荐答案

首先,你可以从一个处理程序创建文件 ashx的

First you can create the file from a handler .ashx

让说,你有在 download.ashx 下载文件,你有一些参数应用到您的javascript,例如通过 download.ashx ?P1 = 8827&放大器; P2 = 8831 来知道你要创建什么

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.

然后在你的JavaScript,你可以简单的做一个重定向为

Then on your javascript you simple can make a redirect as

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

或替代,你可以使用 window.open 为做同样认为

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.

只要确保你已经设置附件的标题,在你的句柄如正确的contentType:

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.

这篇关于什么是从服务器下载文件的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆