首页 > 解决方案 > 我将如何选择所有类型的附件,如 pdf、gif、jpg,以链接的形式并在单击链接时下载文件

问题描述

我可以选择并显示图像,但我需要将其显示为链接,然后单击链接下载

$imagesDirectory =basename("images/"); //path to directory

if (is_dir($imagesDirectory))
{
    $opendirectory = opendir($imagesDirectory); // to read images from path

    while (($image = readdir($opendirectory)) !== false)
    {
        if(($image == '.') || ($image == '..'))
        {
         continue;
        }

        $imgFileType = pathinfo($image,PATHINFO_EXTENSION);

        if(($imgFileType == 'jpg') || ($imgFileType == 'png')) //Types of files
        {
            echo "<img src='images/".$image."' width='200'> ";
        }
    }

    closedir($opendirectory);
 }
?>

标签: phpimagedownload

解决方案


您非常接近答案,只需将图像包装在锚标记中并将“下载”属性传递给它。而已:

$imagesDirectory =basename("images/"); //path to directory

if (is_dir($imagesDirectory))
{
    $opendirectory = opendir($imagesDirectory); // to read images from path

    while (($image = readdir($opendirectory)) !== false)
    {
        if(($image == '.') || ($image == '..'))
        {
         continue;
        }

        $imgFileType = pathinfo($image,PATHINFO_EXTENSION);

        if(($imgFileType == 'jpg') || ($imgFileType == 'png')) //Types of files
        {
            /*xxxxxxxxxxxx-----Here's the Change-----xxxxxxxxxxxx*/
            echo "<a href='images/".$image."' download><img src='images/".$image."' width='200'> </a>";
        }
    }

    closedir($opendirectory);
 }
?>

推荐阅读