duannai5879 2015-01-14 13:04
浏览 41
已采纳

如何使用php和ajax强制下载图像而不显示它

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

  • 写回答

1条回答 默认 最新

  • duanbeng1923 2015-01-14 13:30
    关注

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?