在服务器中创建文件后,使用jQuery下载文件

当我单击客户端上的按钮时,我想使用AJAX在服务器端调用公共静态web方法。 静态方法将创建适当的文件。 创建文件后,我需要将其下载到客户端桌面。 我找到了John Culvinar的jquery filedownload插件,但到目前为止还没有实现它。 我知道使用这个插件还需要编写一个cookie,以便它知道下载完成。 我在哪里将此代码放在服务器端? 创建文件后? 如果有人能在这个场景中向我展示一个样本,我可能会很高兴,也许是在jsfiddle.net上

我建议用隐藏的iframe替换你的ajax请求,然后当你的服务器返回所述文件时,它会自动要求用户下载它。

 //name of iframe var strName = ("uploader" + (new Date()).getTime()); // the iframe var jFrame = $( "" ).css( "display", "none" ); jFrame.load(function( objEvent ){ // at this point the user should have been asked to download a file. // Remove the iFrame from the document. // Because FireFox has some issues with // "Infinite thinking", let's put a small // delay on the frame removal. setTimeout(function(){ jFrame.remove(); },100); }); var form = $('
').attr( "action", "upload_act.cfm" ) .attr( "method", "post" ) .attr( "enctype", "multipart/form-data" ) .attr( "encoding", "multipart/form-data" ) .attr( "target", strName ); form.append('').val("someval"); $( "body:first" ).append( jFrame, form );

(以上代码原文改编自http://www.bennadel.com/blog/1244-ColdFusion-jQuery-And-AJAX-File-Upload-Demo.htm )

另一种方法是将其分为两个步骤。 步骤1生成文件并返回URL,用户单击下载的步骤2(这将是指向所述URL的锚标记)。

如果您想使用jquery插件来增强用户体验,则无法从服务器启动下载。 在这种情况下,最好的办法是在服务器上生成文件,并让该方法返回文件的路径。 然后只是使用插件dl。

例:

 $('#btnID').click(function(){ $.ajax({ type: "POST", url: "/your_webmethod_url", data: "{'webmethodParam1':'val1','webmethodParam2':'val2'}", contentType: "application/json; charset=utf-8", dataType: "json", success: fileGenerated, error: fileNotGenerated }); }); function fileGenerated(data, textStatus, jqXHR){ //this is the success callback method. start download automatically using the plugin $.fileDownload(data.d); //returned data from webmethod goes in data.d } function fileNotGenerated(jqXHR, textStatus, errorThrown){ //this is the error callback method. do something to handle the error alert(errorThrown); }