且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Webservice和jQuery Ajax在客户端下载文件

更新时间:2022-05-27 01:57:23

你实际上并不是真的需要创建WebService以执行操作以让客户端下载文件。你要做的是为用户下载文件的文件链接(通常是页面)创建一个超链接。



You actually didn't really need to create a WebService to perform an action to just let the client download the file. What you would do, is to create a hyperlink for the file link (generally to the page) from where the user would download the file.

<a href="~/DownloadFile?FileName=@Filename">Download</a>
<!-- Where Filename will be populated by a server-side variable
     Can be anything, but would be used on the server-side to push the file -->





现在,一旦用户到达该页面,您就可以将该文件中的数据推送给用户。





Now once the user has reached that page, you can push the data inside that file to the user.

@{
    Layout = null;
    // Get the filename
    var file = Server.MapPath("~/files/" + Request["FileName"]);
    Response.AppendHeader("content-disposition", "attachment; filename=" + Request["img"]);
    Response.ContentType = "application/octet-stream";
    // Now transmit the file
    Response.TransmitFile(file);
}





这会将文件从服务器传输到客户端。不需要任何WebService或任何其他复杂的框架。



This would transmit the file from the server to the client. No need for any WebService or any other complex framework.