user967451
user967451

Reputation:

How to force an image to be downloaded?

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

<img id="my_image" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEA/gD+AAD/etc............" />

Instead of telling my users to right click on the image and hit save I want to expose a download link which when clicked will prompt the image to be downloaded. How to achieve this?

Initially my attempt with thus in js:

var path = $('#my_image').attr('src');
window.open('./download.php?file=' + path);

and in download.php:

<?php
    header('Content-Description: File Transfer');
    header("Content-type: application/octet-stream");
    header("Content-disposition: attachment; filename= " . $_GET['file'] . "");
?>

<img src="<?= $_GET['file'] ?>" />

But problem is, Base64 url stirngs are so large it exceeds the GET request byte limit.

I am open to a solution in either JavaScript or PHP.

Upvotes: 3

Views: 7166

Answers (2)

user967451
user967451

Reputation:

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;
});

Upvotes: 2

unloco
unloco

Reputation: 7320

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:

<form method="post" action="./download.php">
  <input type="hidden" name="data" value="/9j/4AAQSkZJRgABAgEA/gD+AAD/etc............" />
  <a href="#" 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.

Upvotes: 8

Related Questions