我是php的新手,希望写一个下载代码,允许用户下载图像。这意味着我已经给出了一个下载链接,点击它,位于服务器上的图像应该开始下载。我尝试了各种选项,如fopen、curl等,但都没有效果。在使用curl时,图像会下载,但不会在下载位置打开。它给出错误提示“无法读取文件头!未知的文件格式。”请帮帮忙,这是我使用的curl代码:
function DownloadImageFromUrl($imagepath)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch,CURLOPT_URL, $imagepath);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
curl_close($ch);
return $result;
}
$imagecontent =DownloadImageFromUrl("http://www.xyz.com/back_img.png");
$savefile = fopen('myimage.png', 'w');
fwrite($savefile, $imagecontent);
fclose($savefile);发布于 2013-02-07 14:55:49
为此,您应该使用http标头。
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
exit($data);mime -图像的MIME类型
filename -下载文件的名称
数据-文件。您可以使用以下命令从其他服务器获取镜像:
$data = file_get_contents('http://www.xyz.com/back_img.png')发布于 2013-02-07 14:53:57
尝尝这个
$imagecontent =DownloadImageFromUrl("http://www.xyz.com/back_img.png");
$savefile = fopen('myimage.png', 'r');
fread($savefile, $imagecontent);
fclose($savefile);发布于 2013-02-07 14:53:30
function downloadFile ($url, $path) {
$newfname = $path;
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}
downloadFile ("http://www.site.com/image.jpg", "images/name.jpg");https://stackoverflow.com/questions/14745232
复制相似问题