当我单击客户端上的按钮时,我想使用AJAX在服务器端调用公共静态web方法。静态方法将创建适当的文件。创建文件后,我需要将其下载到客户端桌面。我已经找到John Culvinar的jquery filedownload插件,但到目前为止还无法实现。我知道使用此插件还需要编写一个cookie,以便它知道下载已完成。该代码在服务器端放在哪里?创建文件后?如果有人可以在这种情况下(例如在jsfiddle.net上)给我展示示例,我将非常高兴
我建议用隐藏的iframe代替ajax请求,然后当服务器返回上述文件时,它将自动要求用户下载它。
//name of iframe var strName = ("uploader" + (new Date()).getTime()); // the iframe var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" ).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 = $('<form>').attr( "action", "upload_act.cfm" ) .attr( "method", "post" ) .attr( "enctype", "multipart/form-data" ) .attr( "encoding", "multipart/form-data" ) .attr( "target", strName ); form.append('<input type="hidden" name="somename">').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的锚标记)。