Java 如何使用Jquery从httpServlet下载文件?
在我的应用程序中,在客户端创建一个json对象。该对象被发布到一个HttpServlet,该servlet根据发布数据创建一个pdf文件 将文件发送回用户。调用success函数,并记录流数据。但是,我希望该文件已下载 如何做到这一点 我的客户端代码:Java 如何使用Jquery从httpServlet下载文件?,java,jquery,servlets,post,Java,Jquery,Servlets,Post,在我的应用程序中,在客户端创建一个json对象。该对象被发布到一个HttpServlet,该servlet根据发布数据创建一个pdf文件 将文件发送回用户。调用success函数,并记录流数据。但是,我希望该文件已下载 如何做到这一点 我的客户端代码: $(document).ready(function() { // when the print button is clicked $('#exportButton').click(function() { var tableIdx
$(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:
@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
现在,当我单击导出按钮时,表单中的隐藏字段将获取要发布的数据,数据将以www表单编码的形式发布
通过这种方式,servlet可以处理请求,并将文件下载到客户端 不能使用ajax下载文件。出于明显的安全原因,JavaScript没有任何工具可以触发与JavaScript上下文中任意检索/生成的内容的另存为对话。如果可能的话,万维网看起来会大不一样 如果您坚持使用JS/jQuery,那么您需要发送一个synchronus GET请求。您可以使用
window.location
(只需将doPost()
重命名为doGet()
)
或者,扔掉所有不必要的JS/jQuery,只需将普通HTML
与
结合使用即可。额外的好处是,它可以在禁用JS的浏览器中工作
如果您抓取ajax的唯一原因实际上是天真地试图避免刷新页面,那么我可以告诉您,如果响应具有
内容处置:附件标题,则不会发生这种情况。因此,该部分已经是安全的。您不能使用ajax强制下载文件。ajax响应不允许下载文件。他的请求是一篇博文。我必须处理这个问题。所以基本上我会让用户发布其内容,创建一个pdf文件,将其写入服务器上的磁盘,并向用户提供一个链接,用户可以从中下载文件?@SotiriosDelimanolis我认为使用表单是不可能的,但我会检查它。jorrebor,只需写PDF来回复。和你现在一样。您的servlet完全正常。你唯一的问题是如何调用它。这应该是同步的,而不是异步的。我想纠正我前面评论中的“您的servlet完全正常”语句。事实并非如此。如果您的输入已经以字节[]
的形式完全存储在内存中,那么整个读/写循环就完全没有必要了。只需执行response.getOutputStream().write(pdf.toByteArray())代码>。请注意,如果PdfHandler
立即写入response.getOutputStream()
,而不是创建内存中的字节[]
,则效率会更高。但这一切与发送文件下载的实际功能无关。
<button id="exportButton">export</button>
<form id="exportForm" method="post" action="pdfServlet">
<input type="hidden" value="empty" id="pdf_data" name="pdf_data" />
</form>
$('#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();
});
window.location = 'pdfServlet?param1=value1¶m2=value2';