jQuery.ajax servlet返回文件 [英] jQuery.ajax servlet return a file
本文介绍了jQuery.ajax servlet返回文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对jQuery和ajax还是很陌生,我有一个问题. 在一个jsp中,我叫
I'm pretty new to jQuery and ajax and i have a question. In a jsp I call
function downloadDocument(documentId){
var action = "attachment.do";
var method = "downloadDocument";
var url = action + "?actionType="+method+"&documentId=" + documentId;
$.ajax({
url: url,
dataType: "json",
type: 'POST',
success: function(data){
alert("downloaded!");
},
error: function (request, status, error) {
alert(request.responseText);
}
});
然后在servlet中完成
then in the servlet I do
public void downloadDocument(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IOException{
AttachmentActionForm form = (AttachmentActionForm)actionForm;
ServletOutputStream out = response.getOutputStream();
try{
// Get the downloadFileName, the name of the file when it will be downloaded by user
String downloadFileName = "hello.txt";
String mimetype = "application/x-download"
// Get the byte stream of the file
FileInputStream in = new FileInputStream(Global.ATTACHMENTS_SHARED_FOLDER_PATH + downloadFileName);
// Print out the byte stream
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
response.addHeader("Content-Disposition", "attachment; filename="+downloadFileName);
response.setHeader("Content-Length", Integer.toString(length));
response.setContentType(mimetype);
in.close();
}
catch(Exception e){
response.setContentType("text/text;charset=utf-8");
response.setHeader("cache-control", "no-cache");
System.out.println(e.getMessage());
out.println(e.getMessage());
}finally{
out.flush();
}
}
但是在ajax函数中,即使消息由文件内部的字符串组成,我也始终无法获得成功.我该怎么办?
But in the ajax function, I never get a success, all the time I get the error message, even if the message is composed by the string inside of the file. What can I do?
推荐答案
不要使用Ajax调用,//不要使用隐藏表单方法
dont use Ajax call use //use hidden form approach
<form action='../servletname' method='POST' id='formid'>
<input type='hidden' value='' name='name' id='id'/>
<input type='hidden' value=' ' name='name' id='id' />
</form>
点击按钮提交表单
$('#formid').submit();
在servlet中
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=filnemae.fileformat");
ServletOutputStream out = res.getOutputStream();
写输出流,然后关闭或刷新
write on ouput stream then close or flush
如果您通过server.xml中的post update postsize发送大数据
if you are sending large data through post update postsize in server.xml
这篇关于jQuery.ajax servlet返回文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文