Skip to content

Instantly share code, notes, and snippets.

@klkucan
Last active November 14, 2017 17:28
Show Gist options
  • Save klkucan/70b5f791ddb588ddaf76da7c7ff5871e to your computer and use it in GitHub Desktop.
Save klkucan/70b5f791ddb588ddaf76da7c7ff5871e to your computer and use it in GitHub Desktop.
Unity从PHP服务器下载文件
IEnumerator GetFile()
{
string path = "D:\\Resource4Code\\php\\file\\";
Debug.Log(path);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
UnityWebRequest www = new UnityWebRequest("127.0.0.1/filedownload.php");
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.SendWebRequest();
if (www.isHttpError || www.isNetworkError)
{
Debug.Log(www.responseCode);
yield break;
}
else
{
File.WriteAllBytes(path + "aaa.txt", www.downloadHandler.data);
Debug.Log("go to " + path);
}
}
<?php
header("Content-type:text/html;charset=utf-8");
// $file_name="cookie.jpg";
$file_name = "aaa.txt";
//用以解决中文不能显示出来的问题
$file_name = iconv("utf-8", "gb2312", $file_name);
$file_sub_path = $_SERVER['DOCUMENT_ROOT'] . "/file1/";
$file_path = $file_sub_path . $file_name;
//首先要判断给定的文件存在与否
if (!file_exists($file_path)) {
//header('HTTP/1.1 404 Not Found'); // 这个也没问题
http_response_code(404);
// echo "没有这个文件:" . $file_path;
return;
}
$fp = fopen($file_path, "r");
$file_size = filesize($file_path);
//下载文件需要用到的头
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length:" . $file_size);
Header("Content-Disposition: attachment; filename=" . $file_name);
$buffer = 1024;
$file_count = 0;
//向浏览器返回数据
while (!feof($fp) && $file_count < $file_size) {
$file_con = fread($fp, $buffer);
$file_count += $buffer;
echo $file_con;
}
fclose($fp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment