如何使用Jquery从httpServlet下载文件? [英] How to download file from httpServlet with Jquery?
问题描述
在我的应用程序中,在客户端创建了一个json对象。此对象发布到HttpServlet,它根据POST数据创建pdf文件。
In my application, a json object is created on client side. This object is posted to a HttpServlet which creates a pdf file based on the POST data.
该文件将发回给用户。调用succes函数,并记录流数据。但是,我想要下载该文件。
The file is send back to the user. The succes function is called, and stream data is logged. I want however, that the file is downloaded.
如何实现这一目标?
我的客户代码:
$(document).ready(function() {
// when the print button is clicked
$('#exportButton').click(function() {
var tableIdx = performanceDetailTableController.getTableIdx();
var allData = {
"shipTable1":{
"rows":[
{ "latitude":"12323","longitude":"213213"},
{ "latitude":"213213","longitude":"543543"}
]},
"shipTable2":{
"rows":[
{ "latitude":"12323", "longitude":"213213"},
{ "latitude":"213213","longitude":"543543"}
]}
}
var postData = JSON.stringify(allData);
$.ajax({
type : "POST",
url : 'pdfServlet',
contentType: "application/json; charset=utf-8",
data : postData,
async : false,
success : function(data) {
alert("got some data");
console.log(data);
},
});
});
});
和servlet创建文件:
And the servlet creating the file:
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// get the json content
StringBuffer jsonContent = getPostedContent(request);
log.info(jsonContent.toString());
// convert json to pojo's
Tables tables = getTablesFromString(jsonContent);
// create a xml stream
ByteArrayOutputStream xml = new XmlConverter().getXMLSource(tables);
// put the xml on the request
request = setXmlOnRequest(request, xml);
// create pdf data of the pdf-able xml content
ByteArrayOutputStream pdf = new PdfHandler().createPdfDataStream(request);
// response = createResponseheaders(response, request);
response.setContentType("application/pdf");
response.setContentLength(pdf.size());
response.setHeader("Content-disposition", "attachment; filename=test.pdf");
response.setCharacterEncoding("utf-8");
response.getOutputStream().write(pdf.toByteArray());
//close the streams
pdf.close();
response.getOutputStream().close();
}
日志中的输出:
%PDF-1.4
%
4 0 obj
<<
/Producer (Apache FOP Version SVN branches/fop-0_95)
/CreationDate (D:20130725162007+02'00')
>>
endobj
5 0 obj
<<
/N 3
/Length 11 0 R
/Filter /FlateDecode
>>
stream
xwTSϽ7PhRHH.*1 J
* 我的解决方案: *
参见 http://www.particletree.com/notebook/ajax-file-download-or-not/ 指针
I创建了一个包含一个隐藏字段的表单:
I created a form with one hidden field:
<button id="exportButton">export</button>
<form id="exportForm" method="post" action="pdfServlet">
<input type="hidden" value="empty" id="pdf_data" name="pdf_data" />
</form>
比我将我的jquery post数据控制器更改为:
than i changed my jquery post data controller to:
$('#exportButton').click(function() {
var tableIdx = performanceDetailTableController.getTableIdx();
var allData = {
"shipTable1":{
"rows":[
{ "latitude":"12323","longitude":"213213"},
{ "latitude":"213213","longitude":"543543"}
]},
"shipTable2":{
"rows":[
{ "latitude":"12323", "longitude":"213213"},
{ "latitude":"213213","longitude":"543543"}
]}
}
var postData = JSON.stringify(allData);
// put the data on the hidden form field in the export form
$('#pdf_data').val(postData);
// and submit the form
$('#exportForm').submit();
});
所以现在当我点击导出按钮时,表单中的隐藏字段会获取要发布的数据数据以www-form编码方式发布。
so now when i click the export button, the hidden field in the form gets the data to post and the data is posted as www-form encoded.
这样servlet可以处理请求,并将文件下载到客户端。
This way the servlet can handle the request and the the file is downloaded to the client.
推荐答案
您无法使用ajax下载文件。出于明显的安全原因,JavaScript无法触发与JavaScript上下文中任意检索/生成的内容的另存为对话。如果可能的话,万维网看起来会有很大差异。
You can't download files with ajax. JavaScript has for obvious security reasons no facilities to trigger a Save As dialogue with arbitrarily retrieved/generated content in JavaScript context. The world wide web would have looked very different if that was possible.
如果你坚持使用JS / jQuery,你需要发送一个同步GET请求。您可以使用 window.location
(您只需将 doPost()
重命名为 doGet()
)。
If you insist in using JS/jQuery for that, you need to send a synchronus GET request instead. You can do that with window.location
(you only need to rename doPost()
to doGet()
).
window.location = 'pdfServlet?param1=value1¶m2=value2';
或者,只需丢弃所有不必要的JS / jQuery并使用纯HTML < form action =pdfServletmethod =post>
with < input type =submit>
。额外的好处是它可以在禁用JS的浏览器中运行。
Alternatively, just throw away all that unnecessary JS/jQuery and just use plain HTML <form action="pdfServlet" method="post">
with <input type="submit">
. Additional bonus is that it works in browsers with JS disabled.
如果您获取ajax的唯一理由实际上是避免页面被刷新的天真尝试,那么我可以告诉如果响应有一个 Content-Disposition:attachment
标题,那么这真的不会发生。所以这部分已经安全了。
If your sole reason to grab ajax is actually a naive attempt to avoid the page being refreshed, then I can tell you that this really won't happen if the response has a Content-Disposition: attachment
header. So that part is already safe.
这篇关于如何使用Jquery从httpServlet下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!