I have created a zip file in my servlet. Now I would like to trigger that servlet using Ajax and prompt the download dialog to the user. I can trigger the servlet, but I don't know how to get the save dialog. How can I achieve this?
相关问题
- Carriage Return (ASCII chr 13) is missing from tex
- Using :remote => true with hover event
- Is there a way to play audio on a mobile browser w
- net::ERR_EMPTY_RESPONSE when post with ajax
- Easiest way to get json and parse it using JQuery
相关文章
- spring boot用ajax发送请求后,请求路径多了controller的路径
- 针对复杂结构的前端页面,如何更好地与后台交互实现动态网页?
- ajax上传图片,偶尔会出现后台保存的图片有错误或者已损坏,请问可能是什么原因造成的?
- 前端 我想知道怎样通过发ajax请求向服务器拿到数据然后分页显示 最好是点击一页就发一次请求
- 接口返回的数据格式如下,请问可以取到level值为2的name数组呢
- 如何通过页面输入账号密码提交给后端
- How to get jQuery.ajax response status?
- How to read local csv file in client side javascri
You can't use Ajax for this. You basically want to let the enduser save the file content to the local disk file system, not to assign the file content to a JavaScript variable where it can't do anything with it. JavaScript has for obvious security reasons no facilities to programmatically trigger the Save As dialog whereby the file content is provided from an arbitrary JavaScript variable.
Just have a plain vanilla link point to the servlet URL and let the servlet set the HTTP
Content-Disposition
header toattachment
. It's specifically this header which will force the browser to pop a Save As dialog. The underlying page will stay same and not get refreshed or so, achieving the same experience as with Ajax.Basically:
That could also be done in JavaScript as below without firing a whole Ajax call:
Alternatively, if you're actually using POST for this, then use a (hidden) synchronous POST form referring the servlet's URL and let JavaScript perform a
form.submit()
on it.See also:
You can't "download a file using AJAX". AJAX is about downloading data from a server for JavaScript to process.
To let the user download the file either use a simple link to the file/servlet, or if you really, really need to use JavaScript, then assign the URL to
document.location.href
.Also you need to make sure that the server (or in this case the servlet) sends the appropriate MIME type, in case of a ZIP file most likely
application/zip
.