dsff788655567 2013-05-29 18:15
浏览 33
已采纳

为图像添加下载选项

I have a PHP script that is working fine for displaying all my images in a directy that I upload to. I wand to make a little download button so someone can click the button and download the image. I am making this for my company so people can download our logos.

<?php
        // Find all files in that folder
        $files = glob('grips/*');

        // Do a natural case insensitive sort, usually 1.jpg and 10.jpg would come next to each other with a regular sort
        natcasesort($files);


        // Display images
        foreach($files as $file) {
           echo '<img src="' . $file . '" />';
        }

    ?>

I figue I could just make a button and call the href of $file but that would just link to the file and show the image. I am not sure to have it auto download. Any help would be great.

  • 写回答

1条回答 默认 最新

  • doujiao9866 2013-05-29 18:18
    关注

    Just add some headers in a download.php file so you can then read the file in like this:

    Make sure you sanitize your data coming to the file, you don't want people to be able to download your php files.

    <?php
        // Find all files in that folder
        $files = glob('grips/*');
    
        // Do a natural case insensitive sort, usually 1.jpg and 10.jpg would come next to each other with a regular sort
        natcasesort($files);
    
    
        // Display images
        foreach($files as $file) {
           echo '<img src="' . $file . '" /><br /><a href="/download.php?file='.base64_encode($file).'">Download Image</a>';
        }
    
    ?>
    

    download.php

    $filename = base64_decode($_GET["file"]);
    
    // Data sanitization goes here
    if(!getimagesize($filename) || !is_file($filename)){
        // Not an image, or file doesn't exist. Redirect user
        header("Location: /back_to_images.php");
        exit;
    }
    
    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Content-Type: application/force-download"); 
    header("Content-Type: application/octet-stream"); 
    header("Content-Type: application/download"); 
    header("Content-Disposition: attachment; filename=".basename($filename).";"); 
    header("Content-Transfer-Encoding: binary"); 
    header("Content-Length: ".filesize($filename)); 
    
    readfile($filename); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?