【问题标题】:PHP force download .png filePHP强制下载.png文件
【发布时间】:2016-04-01 00:34:20
【问题描述】:

您好,感谢您抽出宝贵时间。

我正在尝试使用以下代码强制将一个 .png 图像下载到用户计算机上,该图像是从我开发的 Unity 应用程序创建的。

    <?php
    //get the input information
    $stringName = $_POST["stringName"];//name
    $imageString = $_POST["imageString"];//image in string form

    $dataX = base64_decode($imageString);//make the string into the image
    file_put_contents($stringName, $dataX);//save the image on the server
//everything thing above this line works within Unity

    $fileSize = filesize($stringName);//get the file size

    //bunch of headers, comments next to the ones I have an idea about
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header("Content-Type: imagepng");//gives content type
    header("Content-Length: ".$fileSize);//file size
    header("Content-Disposition: attachment; filename=".$stringName);//download file path
    header("Content-Transfer-Encoding: binary");
    ob_clean();
    flush();
    readfile( $stringName );
?>

我有这个,但它没有弹出下载确认框,也没有对提供的图像做任何事情。

在浏览器中运行我的程序时,调用上述脚本时出现两个错误之一。由于我从保管箱托管应用程序,我得到“无法从 https 发送到 http”,当我将 php 文件的地址更改为 https 时,它会超时。

首先,有没有办法获得 https 和 http 以允许两者之间的通信,我宁愿不必在 ftp 服务器上托管我的统一项目,因为我有几个项目以相同的方式设置。其次,该 PHP 脚本是否可以正常工作,如果可以,我可以删除一些内容吗?

【问题讨论】:

  • 您能否提供有关 http/https 问题的更多信息?
  • 混合内容:“URL”处的页面通过 HTTPS 加载,但请求了不安全的 XMLHttpRequest 端点“URL”。此请求已被阻止;内容必须通过 HTTPS 提供。是我从控制台得到的错误。

标签: c# php unity3d download ftp


【解决方案1】:

以下代码将成功强制下载文件“example.png”:

<?php

// requested file's name
$file_name = "example.png";

// make sure it's a file before doing anything
if(is_file($file_name))
{
  // required for IE
  if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }

  // get the file mime type using the file extension
  switch(strtolower(substr(strrchr($file_name,'.'),1)))
  {
      case 'pdf': $mime = 'application/pdf'; break;
      case 'zip': $mime = 'application/zip'; break;
      case 'jpeg':
      case 'jpg': $mime = 'image/jpg'; break;
      case 'png': $mime = 'image/png'; break;
      default: $mime = 'application/force-download';
  }
  header('Pragma: public');   // required
  header('Expires: 0');       // no cache
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Cache-Control: private',false);
  header('Content-Type: '.$mime);
  header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
  header('Content-Transfer-Encoding: binary');
  header('Content-Length: '.filesize($file_name));    // provide file size
  readfile($file_name);       // push it out
}

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2012-08-03
    • 2010-11-03
    • 2010-11-30
    相关资源
    最近更新 更多