2012-12-19 50 views
4

當我點擊客戶端的按鈕時,我想使用AJAX在服務器端調用公共靜態webmethod。靜態方法將創建適當的文件。文件創建後,我需要將其下載到客戶端桌面。我發現了John Culvinar's jquery filedownload plugin,但迄今尚未實現。我知道使用這個插件還需要編寫一個cookie,以便它知道下載完成。我在哪裏把這個代碼放在服務器端?在創建文件後?我很高興如果有人能給我一個樣本在這種情況下,也許在jsfiddle.net在服務器中創建後使用jQuery下載文件

+0

如果你可以通過一個URL創建文件(可能是每個會話)來訪問該文件,並且將content-disposition設置爲附件,那麼只需使用'window.location = path_to_file'就行了。 –

+1

我建議用隱藏的iframe替換您的ajax請求,然後當您的服務器返回所述文件時,它會自動要求用戶下載它。另一種方法是將其分爲兩個步驟。第1步生成文件並返回一個url,第2步用戶單擊下載(這將是指向所述url的錨標記)。 –

+0

@KevinB,你可以請你的評論作爲答案,並給我一個示例代碼做這個? –

回答

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

另一種方法是,使之成爲兩個步驟過程。第1步生成文件並返回一個url,第2步用戶單擊下載(這將是指向所述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); 
} 
相關問題