图片远程保存,浏览器直接下载

     $url = '远程图片';
        $url      = preg_replace( '/(?:^[\'"]+|[\'"\/]+$)/', '',$url] ); //url过虑
        $fn         = "Dowload/voluntary.jpg"; //保存路径
        header('Content-type:text/html;charset=utf-8');    
        $image_info = getimagesize($url);        
        $base64_image_content = "data:{$image_info['mime']};base64," . chunk_split(base64_encode(file_get_contents($url))); //编码
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){    //保存本地
            @unlink($fn);
            $type = $result[2];
            $a = file_put_contents($fn, base64_decode(str_replace($result[1], '', $base64_image_content))); //保存
            //文件下载
            header('Content-type: application/x-jpg');
            //下载显示的名字
            header('Content-Disposition: attachment; filename="voluntary.jpg"');
            ob_clean();  
              flush();  
              readfile($fn); //浏览器直接下载
            exit();
        }

 

posted @ 2018-12-06 17:08  Kris-Q  阅读(299)  评论(0)    收藏  举报