2012-09-14 20 views
0

我有以下情況: 我必須動態地創建文件,用戶代理通過AJAX將數據發送到服務器以這樣的方式最近創建的文件不能下載

$("#generateButton").live("click",function(){ 
dateLimite = $("#dateLimite").val(); 
$.ajax({ 
    type : "POST", 
    url  : "../generateFile.do", 
    data : { fileName: "demandeExplication", 
    nbrParam: "3", 
    param1:"<%=agent.getPrenomAgentArabe()+" "+agent.getNomAgentArabe()%>", 
    param2:"<%=descriptionActe%>", 
    param3:dateLimite, 
    }, 
    dataType: "html", 

}).done(function(data) { 
$("#test").empty().append(data); 
    fileName = $("#test").find("input").val(); 
$.fileDownload('http://localhost:8080/gestionRH/fiches/temp/'+fileName); 

}); 
}); 

服務器進程本與創建一個文件dynamicaly動作數據:

public class GenerateFile extends Action 
{ 



public ActionForward execute(ActionMapping mapping, ActionForm form, 
     HttpServletRequest request, HttpServletResponse response) throws IOException { 
    String fileName = request.getParameter("fileName"); 
    Integer nbrParam = Integer.parseInt(request.getParameter("nbrParam")); 
    String[] valueParam = new String[nbrParam+1]; 
    for(int i =1;i<=nbrParam;i++) 
    { System.out.println(request.getParameter("param"+i)); 
     valueParam[i]=request.getParameter("param"+i); 
    } 
    FileInputStream in = new FileInputStream("C:\\Users\\free\\Desktop\\myworkspace\\gestionRH\\WebRoot\\fiches\\"+fileName+".doc"); 
    POIFSFileSystem fs = new POIFSFileSystem(in); 
    HWPFDocument doc = new HWPFDocument(fs); 
    Range r = doc.getRange(); 
    for(int i=1;i<=nbrParam;i++) 
    { System.out.println("<param"+i+">"); 
     System.out.println(valueParam[i]); 
     r.replaceText("<param"+i+">", valueParam[i]); 
    } 


    File frr = new File("C:\\Users\\free\\Desktop\\myworkspace\\gestionRH\\WebRoot\\fiches\\temp"); 
    File temp = File.createTempFile("monfile",".doc",frr); 
    FileOutputStream out = new FileOutputStream(temp); 
    doc.write(out); 
    out.close(); 
    in.close(); 
    request.setAttribute("fileName", temp.getName()); 
    return mapping.findForward("fileName"); 
} 
} 

我使用這個插件做下載:http://johnculviner.com/category/jQuery-File-Download.aspx

,我收到了n錯誤下載! 我不與已存在的文件獲得,或當我引發一些時間與此代碼後下載:

function timeout_trigger() {  

文件名= $(「#測試」)找到(「輸入」)VAL。 (); }

至極我使用這種方式:

......}).done(function(data) { 
setTimeout("timeout_trigger()",7000); 
}); 

和第二個解決方案並不總是工作,所以我必須解決這個問題。 爲什麼已經下載的文件沒有問題,並且最近在下載時創建了顯示錯誤?

+0

似乎是一個計時問題,其中http請求創建文件已完成,但服務器還沒有實際完成生成文件。在你的服務器端代碼中,你是結束請求並在另一個線程上處理文件,還是應該在請求結束之前完成? –

+0

通常它應該在請求結束前完成,因爲它會將文件的名稱返回給客戶端以便下載它 – fatiDev

回答

2

這可能是因爲該文件尚未上傳。使用AJAX,文件將在後臺上傳。這需要時間。服務器代碼只有在整個文件被上傳後才被觸發(它不希望在部分文件上運行)。

所以你需要的是一種方法來問:「有沒有上傳這個進程?」。當我遇到同樣的問題時,我發送了幾個AJAX請求。第一個會在會話中創建一個狀態對象,我將記錄文件名。

當查詢文件時,我會查看該狀態對象以查看上傳是否完成並返回狀態。

還有方法掛鉤上傳過程;當你這樣做時,你甚至可以添加一個「上傳百分比」到狀態對象。