下载一个文件jQuery.Ajax [英] Download a file by jQuery.Ajax
问题描述
我有一个Struts2的动作,在服务器侧进行文件下载。
I have a Struts2 action in the server side for file downloading.
<action name="download" class="com.xxx.DownAction">
<result name="success" type="stream">
<param name="contentType">text/plain</param>
<param name="inputName">imageStream</param>
<param name="contentDisposition">attachment;filename={fileName}</param>
<param name="bufferSize">1024</param>
</result>
</action>
然而,当我打电话使用jQuery的操作:
However when I call the action using the jQuery:
$.post(
"/download.action",{
para1:value1,
para2:value2
....
},function(data){
console.info(data);
}
);
在Firebug我看到的数据是retreived与二进制文件的流。我不知道如何打开文件下载窗口与用户可以在本地保存文件?
in Firebug I see the data is retreived with the Binary stream. I wonder how to open the file downloading window with which the user can save the file locally?
推荐答案
偏蓝是完全正确的这一点,你可以T做到这一点,通过Ajax的,因为JavaScript不能直接将文件保存到用户的计算机(出于安全考虑)。不幸的是指向的主窗口的URL在你的文件下载意味着你无法控制用户体验是什么时,文件下载发生。
Bluish is completely right about this, you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns). Unfortunately pointing the main window's URL at your file download means you have little control over what the user experience is when a file download occurs.
我创建的<一个href="http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx">jQuery文件下载它允许一个阿贾克斯像用文件下载完成的onSuccess和OnFailure回调提供更好的用户体验体验。看看我的<一个href="http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx">blog帖子的共同问题,即插件解决了一些办法来利用它,也是jQuery的文件下载一个演示在行动A> 。这里是<一个href="http://github.com/johnculviner/jquery.fileDownload/blob/master/src/Scripts/jquery.fileDownload.js">source
I created jQuery File Download which allows for an "Ajax like" experience with file downloads complete with OnSuccess and OnFailure callbacks to provide for a better user experience. Take a look at my blog post on the common problem that the plugin solves and some ways to use it and also a demo of jQuery File Download in action. Here is the source
下面是一个使用该插件<一个简单的用例演示href="http://github.com/johnculviner/jquery.fileDownload/blob/master/src/Scripts/jquery.fileDownload.js">source与承诺。该演示页面包含了许多其他的,更好的UX的例子也是如此。
Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.
$.fileDownload('some/file.pdf')
.done(function () { alert('File download a success!'); })
.fail(function () { alert('File download failed!'); });
这篇关于下载一个文件jQuery.Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!