Skip to content Skip to sidebar Skip to footer

How To Force An Image To Be Downloaded?

I hava a dynamically generated image on my page like so: Instead of telling my

Solution 1:

Try this in download.php:

<?php
    header('Content-Description: File Transfer');
    header("Content-type: application/octet-stream");
    header("Content-disposition: attachment; filename= Image.jpg");
    exit(base64_decode($_POST['data'])); //url length is limited, use post instead?>

And use this for a form:

<formmethod="post"action="./download.php"><inputtype="hidden"name="data"value="/9j/4AAQSkZJRgABAgEA/gD+AAD/etc............" /><ahref="#"onclick="this.parentNode.submit();return false;">Download</a></form>

like Dagon said this is not the best way to go because submitting the form would be like uploading the whole image.

Solution 2:

Turns out one of the other questions did have the answer:

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

I am doing it strictly on the client sde like so:

$('a#download_image').on('click', function() {
    var url = $('#my_image').attr('src').replace(/^data:image\/[^;]/, 'data:application/octet-stream');
    location.href = url;
});

Post a Comment for "How To Force An Image To Be Downloaded?"