0

I am doing a web application that generates a QR image (PNG format) for a URL. If the URL changes, the image changes too. Here is the HTML (size parameter indicates the size of the QR image):

<div class="image">
    <img src="/img?size=150" />             
    <a href="#">download</a>
</div>

My goal is to the image is downloaded (instead of being rendered by the browser) when a visitor clicks on the download link. How can I do this?

I searched SO and found related posts that use Javascript to download static image. Any difference here?

Update

I found out this SO link works for me.

Download File Using Javascript/jQuery

Actually there is difference the image is dynamically generated or static. Besides, it guarantees the download for any file types regardless of browser settings.

halfer
  • 19,824
  • 17
  • 99
  • 186
curious1
  • 14,155
  • 37
  • 130
  • 231

2 Answers2

1

if I understood your problem well, you can do it like in my example on JsFiddle (I used jQuery here): https://jsfiddle.net/v6qboyfm/

Here is code:

$('a').on('click', function(e) {
   var src = ($(e.currentTarget).closest('.image').find('img')[0].src);
   $(e.currentTarget).attr('download', src);
   $(e.currentTarget).click();
   e.preventDefault();
});
Štefan Ondáš
  • 358
  • 1
  • 5
  • 18
  • Hi Stefan, thanks for chiming in! Your approach cannot prevent the browser from rendering it. Actually, I found out this link works well for me: http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery – curious1 Nov 11 '16 at 15:56
1

If you can use dynamic source for your image then you can use that in your anchor too.As far as browser is concerned ,there is no difference between an actual image and one generated dynamically through some php script.So you can use the download property trick to make it work just any using php

<div class="image">
  <img src="/img?size=150" />             
  <a href="/img?size=150" download="/img?size=150">download</a>
</div>
Vinay
  • 7,442
  • 6
  • 25
  • 48
  • Novice, thanks for your input. I found out my solution. I upvoted your input too. – curious1 Nov 11 '16 at 15:58
  • That's cool but if you use this solution then you won't need any javascript – Vinay Nov 11 '16 at 16:00
  • Your way cannot prevent the browser opening a file. What I need is download in any browser and for any types of files no matter what the browser settings are. Thanks! – curious1 Nov 11 '16 at 16:04
  • 1
    I see , I have used it many times for a asp.net project it worked perfect but that was all on desktop so not sure about mobile.I agree with you – Vinay Nov 11 '16 at 16:09
  • 1
    Besides, your approach also depends on the browser settings. Thanks for coming to help. We all learn being helped and help others. SO is the greatest place for people like us! Best. – curious1 Nov 11 '16 at 16:15