0

私は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);
4

4 に答える 4

2

これには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-07T06:55:49.257 に答える
1

これを試して

$imagecontent =DownloadImageFromUrl("http://www.xyz.com/back_img.png");
$savefile = fopen('myimage.png', 'r');
fread($savefile, $imagecontent);
fclose($savefile);
于 2013-02-07T06:53:57.383 に答える
0

header()ダウンロード可能なアイテムとして開くには、メソッドを追加する必要があります。

header("Content-Type: application/force-download"); 
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" ); 

どこ

$fullPathイメージパスです。

詳細な仕様については、phpの--headerを参照してください。

于 2013-02-07T06:56:32.020 に答える
0
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");
于 2013-02-07T06:53:30.080 に答える