创建文件后使用jQuery下载文件

4
当我在客户端点击一个按钮时,我想使用AJAX调用服务器端的公共静态WebMethod。该静态方法将创建适当的文件。文件创建后,我需要将其下载到客户端桌面。我找到了John Culvinar的jquery filedownload插件,但迄今为止还没有能够实现它。我知道使用此插件还需要编写一个cookie,以便它知道下载已完成。我应该把这段代码放在服务器端的哪里?在创建文件之后吗?如果有人能向我展示这种情况的示例,可能在jsfiddle.net上,我会非常高兴。

如果您可以在创建文件后通过URL访问该文件(可能是每个会话),并将内容设置为附件,则只需使用window.location = path_to_file即可。 - Explosion Pills
1
我建议用一个隐藏的iframe替换你的ajax请求,然后当服务器返回文件时,它会自动要求用户下载。另一种选择是将其变成两个步骤的过程。第一步生成文件并返回URL,第二步用户点击下载(这将是一个指向该URL的锚点标签)。 - Kevin B
@KevinB,请您把您的评论发布为答案,并给我提供一个实现此功能的示例代码好吗? - Mikayil Abdullayev
2个回答

2
我建议使用隐藏的 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改编而来的。
另一种选择是将其变成一个两步骤的过程。第一步生成文件并返回URL,第二步用户点击下载(这将是一个指向该URL的锚点标签)。

1

如果你想使用 jQuery 插件来增强用户体验,你不能从服务器发起下载。在这种情况下,最好的选择是在服务器上生成文件,并使该方法返回文件路径。然后只需要使用插件进行下载。

示例:

$('#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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接