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