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

2023-09-10 14:16:16 作者:硬撑

当我点击客户端我想要调用使用AJAX的服务器端公共静态WebMethod的一个按钮。静态方法将创建相应的文件。创建文件后,我需要把它下载到客户端桌面。我发现约翰Culvinar的jQuery的filedownload插件,但一直没能实现它为止。我知道,使用这个插件还需要编写一个cookie,这样它知道下载完成。我在哪里可以把这个code在服务器端?创建文件后?我会很高兴,如果有人能告诉我在这种情况下的样本,也许在 jsfiddle.net

When I click a button on the client side I want to invoke a public static webmethod on the server side using AJAX. The static method will create the appropriate file. After the file is created I need to download it to the client desktop. I've found John Culvinar's jquery filedownload plugin but haven't been able to implement it so far. I know that using this plugin also requires writing a cookie so that it knows that the download is complete. Where do I put this code in the server side? After creating the file? I'd be very glad if someone could show me a sample on this scenario, maybe on jsfiddle.net

推荐答案

我建议有一个隐藏的iframe更换您的Ajax请求,那么当你的服务器返回表示文件,它会自动询问用户下载。

I suggest replacing your ajax request with a hidden iframe, then when your server returns said file, it will automatically ask the user to download it.

//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 );

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

另一种方法是,使之一个两步骤过程。步骤1产生的文件,并返回一个网址,步骤2中的用户点击下载(这将是一个锚定标记指向所述URL)。

An alternative would be to make it a two step process. Step 1 generates the file and returns a url, step 2 the user clicks download ( which would be an anchor tag pointing at said url).