php接收文件数据流保存文件

作为大家使用这个过程中的一个参考,也是第一次接触接收文件流。

public function actionIndex()
{
header("content-type:application/json");

$filepath=trim(htmlspecialchars(strip_tags($_POST["filepath"])));
$filepath = SafetyHelper::KillDangerCode($filepath);

$result = '{
"components": [
{
"fileLoc": "'.$filepath.'",
"format": "ofd",
"title": "test"
}
],
"type": "custom.ofd2image"
}';

$arr = $this->sendPostData("http://127.0.0.1:8091/sync/common/x2y", "", $result);

//接收二进制文件流数据
$data = $arr;

//获取文件后缀
$fileType = '';
$this->getFileType($data, $fileType);
if ($fileType == 'unknown'){
exit('文件类型识别失败');
}

//拼接文件后缀:生成唯一文件名
$uniqueName = rand(1000,9999).time() . $fileType;

$saveDb = $this->uploadBinaryFile($data, $uniqueName);

return $saveDb;
}

//判断获取文件类型,后缀
function getFileType($file, &$fileType)
{
/* 参考:PHP通过二进制流判断文件类型 https://blog.csdn.net/xwlljn/article/details/85134958 */
// 文件头标识 (2 bytes)
$bin = substr($file,0, 2);
$strInfo = unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'] . $strInfo['chars2']);

/* 参考:利用文件头判断文件类型 https://blog.csdn.net/weixin_34267123/article/details/85506211 */
// 文件头对应的文件后缀关联数组
$fileToSuffix = [
255216 => '.jpg',
7173 => '.gif',
6677 => '.bmp',
13780 => '.png',
208207 => '.xls', //注意:doc 文件会识别成 208207
8075 => '.zip', //注意:xlsx文件会识别成 8075
239187 => '.js',
6787 => '.swf',
7067 => '.txt',
7368 => '.mp3',
4838 => '.wma',
7784 => '.mid',
8297 => '.rar',
6063 => '.xml',
];

$fileType = empty($fileToSuffix[$typeCode]) ? 'unknown' : $fileToSuffix[$typeCode];
}

/**
* 上传二进制文件并保存
* @param $data 文件内容
* @param $uniqueName 唯一文件名
* @param string $path 自定义文件保存目录
* @return string
*/
public function uploadBinaryFile($data, $uniqueName)
{
$Path = "D:\websites/1X_WPSxuexi"; //
$Path = str_replace('\\', '/', $Path); //把 \\ 替换成 /

$relativePath = '/img/'; //文件存放的相对路径(相对应用根目录)
$saveDb = $relativePath . $uniqueName; //存放到数据表的路径
$savePath = $Path . $saveDb; //文件存放的绝对路径
//var_dump($uniqueName);die;
$mkdirPath = $Path . $relativePath;//var_dump($mkdirPath);die;
if (!is_dir($mkdirPath)) { //文件夹不存在,则创建;并给最大权限 777
mkdir($mkdirPath,0777,true);
chmod($mkdirPath,0777);
}

file_put_contents($savePath, $data); //保存文件

return $saveDb;
}

posted @ 2022-04-02 16:43  楠...楠  阅读(1342)  评论(0编辑  收藏  举报