通过 Ajax 调用通过 Web 方法从 C# 下载文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12086999/
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
Download File from C# through Web Method via Ajax call?
提问by Chariji Varun
I have tried to download the file from the server through the webmethod but it has not work for me. my code as below
我试图通过 webmethod 从服务器下载文件,但它对我不起作用。我的代码如下
[System.Web.Services.WebMethod()]
public static string GetServerDateTime(string msg)
{
String result = "Result : " + DateTime.Now.ToString() + " - From Server";
System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["FolderPath"].ToString()) + "\" + "Default.aspx");
System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
//HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.Flush();
Response.End();
return result;
}
and my ajax call code is as below
我的ajax调用代码如下
<script type="text/javascript">
function GetDateTime() {
var params = "{'msg':'From Client'}";
$.ajax
({
type: "POST",
url: "Default.aspx/GetServerDateTime",
data: params,
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
},
error: function (err) {
}
});
}
</script>
and i have called this function in button click..
我在按钮点击中调用了这个函数..
i don't know how to download the file with other methods
我不知道如何用其他方法下载文件
Please suggest me if any other methods available or give the correction in the same code.
请建议我是否有其他可用的方法或在相同的代码中进行更正。
Thanks to all..
谢谢大家..
回答by awe
A WebMethod does not have control of the current response stream, so this is not possible to do this way. At the time you call a web method from javascript, the response stream is already delivered to the client, and there is nothing you can do about it.
WebMethod 无法控制当前响应流,因此无法以这种方式进行。当您从 javascript 调用 Web 方法时,响应流已经交付给客户端,您对此无能为力。
An option to do this is that the WebMethod generates the file as a physical file somewhere on the server, and then returns the url to the generated file to the calling javascript, which in turn uses window.open(...)to open it.
In stead of generating a physical file, you can call some GenerateFile.aspx that does about what you initially tried in your WebMethod, but do it in Page_Load, and call window.open('GenerateFile.aspx?msg=From Clent')from javascript.
执行此操作的一个选项是 WebMethod 将文件生成为服务器上某处的物理文件,然后将生成文件的 url 返回给调用 javascript,后者又用于window.open(...)打开它。
您可以调用一些 GenerateFile.aspx,而不是生成物理文件,它可以完成您最初在 WebMethod 中尝试的操作,但在 .aspx 中执行Page_Load,并window.open('GenerateFile.aspx?msg=From Clent')从 javascript调用 。
回答by Ben
Instead of calling a Web Method it would be a better idea to use a generic handler (.ashx file) and put your code for downloading the file in the ProcessRequest method of the handler.
与其调用 Web 方法,不如使用通用处理程序(.ashx 文件)并将下载文件的代码放在处理程序的 ProcessRequest 方法中。
回答by Ziyad Godil
This is Ajax Call
这是 Ajax 调用
$(".Download").bind("click", function ()
{
var CommentId = $(this).attr("data-id");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TaskComment.aspx/DownloadDoc",
data: "{'id':'" + CommentId + "'}",
success: function (data) {
},
complete: function () {
}
});
});
Code Behind C#
C# 背后的代码
[System.Web.Services.WebMethod]
public static string DownloadDoc(string id)
{
string jsonStringList = "";
try
{
int CommentId = Convert.ToInt32(id);
TaskManagemtEntities contextDB = new TaskManagementEntities();
var FileDetail = contextDB.tblFile.Where(x => x.CommentId == CommentId).FirstOrDefault();
string fileName = FileDetail.FileName;
System.IO.FileStream fs = null;
string path = HostingEnvironment.ApplicationPhysicalPath + "/PostFiles/" + fileName;
fs = System.IO.File.Open(path + fileName, System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(btFile);
HttpContext.Current.Response.End();
fs = null;
//jsonStringList = new JavaScriptSerializer().Serialize(PendingTasks);
}
catch (Exception ex)
{
}
return jsonStringList;
}

