我有以下情况: 我必须动态创建文件,用户代理以这种方式通过 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);
});
});
服务器通过动态创建文件的操作处理此数据:
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
我下载时出错! 我没有得到已经存在的文件,或者当我在一段时间后使用此代码触发下载时:
function timeout_trigger() {
文件名 = $("#test").find("输入").val();
我是这样用的:
......}).done(function(data) {
setTimeout("timeout_trigger()",7000);
});
第二个解决方案并不总是有效,所以我必须解决这个问题。 为什么已经存在的文件可以毫无问题地下载,而最近创建的文件在下载时显示错误?
最佳答案
这可能是因为文件尚未上传。使用 AJAX,文件在后台上传。这需要时间。服务器代码仅在整个文件上传后触发(它不想对部分文件进行操作)。
因此,您需要一种询问“是否有正在进行的上传?”的方法。当我遇到同样的问题时,我发送了几个 AJAX 请求。第一个会在 session 中创建一个状态对象,我会在其中记录文件名。
查询文件时,我会查看状态对象以查看上传是否完成并返回状态。
也有 Hook 到上传过程的方法;当您这样做时,您甚至可以将“上传百分比”添加到状态对象。
关于jquery - 无法下载最近创建的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12424299/