开发者

How can I download image without leaving page?

开发者 https://www.devze.com 2023-01-26 06:37 出处:网络
I have written servlet which actually writes bytes of an image into the response. I am able download the image by submitting form with action get or post to servl开发者_运维百科et. But how can I reque

I have written servlet which actually writes bytes of an image into the response. I am able download the image by submitting form with action get or post to servl开发者_运维百科et. But how can I request this servlet without leaving the page?

I tried jQuery.get("http://localhost:8080/mydownloadservlet"). Request is getting received in servlet but image is not getting download. Same is working with form submit.

Thanks, Amit Patel


Following worked.

Created hidden iframe.

<iframe src="" id="hiddenFrm" style="display:none;" frameborder="0"></iframe>

and using jquery downloaded the image by setting src of hidden frame as follows.

function download(url){
    jQuery("#hiddenFrm").attr("src",url);
}


Add the Content-Disposition: attachment header to the servlet response. This way the client is forced to pop a Save As dialogue.

response.setHeader("Content-Disposition: attachment; filename=image.gif");

Do this before writing any byte to the response. You don't need any JavaScript in the client side for this. Just a link or a form pointing to the servlet. The client won't leave the page because the content disposition is not set to inline.

You're however still dependent on the client's default configuration whether there's a default action associated with the Content-Type of the attachment which will be executed immediately instead of Save As. In Firefox for example, this is configureable by Tools > Options > Applications. You can't control this from the server side on, but you shouldn't worry about this. The client decided itself to have it so.


1) You need to set the HTTP headers correctly:

Content-Disposition: attachment; filename=mypic.jpg

2) You need to navigate to that page, not do jQuery.get, but

<a href="http://localhost:8080/mydownloadservlet">Download pic</a>

or in javascript

window.location = 'http://localhost:8080/mydownloadservlet';

If everything goes according plan, you should actually leave the page.

0

精彩评论

暂无评论...
验证码 换一张
取 消