Search code examples
javascriptphpjqueryajaxdynamic-image-generation

How to force downloading image using php and ajax without displaying it


Here is the php code to generate the image

<?php    

require('class/BCGColor.php');
require('class/BCGDrawing.php');   
require('class/BCGean8.barcode.php');

$font = new BCGFontFile('font/Arial.ttf', 18);
$color_black = new BCGColor(0, 0, 0);
$color_white = new BCGColor(255, 255, 255);

// Barcode Part
$code = new BCGean8();
$code->setScale(2);
$code->setThickness(30);
$code->setForegroundColor($color_black);
$code->setBackgroundColor($color_white);
$code->setFont($font);
$code->parse($_GET['code']);

// Drawing Part
$drawing = new BCGDrawing( '' , $color_white);
$drawing->setBarcode($code);
$drawing->draw();

header('Content-Type: image/png');

$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

header('Content-Disposition: attachment; filename=file.png');    

?>

and this is HTML

<a href="#" >Click</a> <!-- I want to click here to download -->

and Js

$.ajax({
                url: "gen_barcode.php",
                type: 'GET',
                data: {code: '1234567'},
                success: function (data, textStatus, jqXHR) {
                    console.log(data)
                        $('#my_image').attr('src', 'gen_barcode.php?code=1234567');

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(data)
                },

            })

            e.preventDefault();
        })

This script shows the image in the browser, but how to tell browser to download it. I have already used the content disposition in php header. But it is still not working


Solution

  • The image isn't be saved to disk because you are displaying it as the src of an image element.

    If you want the browser to treat Content-Disposition as an instruction for the browser to save it somewhere instead of displaying it, then you need to send the browser to that URL.

    The smallest change you could make to achieve that would be to set location

    success: function (data, textStatus, jqXHR) {
        location = 'gen_barcode.php?code=1234567');    
    },
    

    but it would be simpler to just replace all the JavaScript with a simple link.

    <a href="gen_barcode.php?code=1234567">Save image</a>