TP5 接口模式 图片流保存图片
/**
* @param $img
* 图片流格式
*/
public function setPicRoute($file)
{
if (empty($file)){
return;
}
if(empty($uploadPath)){
$uploadPath = $this->comment_dir; //保存图片的绝对路径
$picr = $this->upload_directory.$this->comment_directory;
}
$img_name = [];
if (is_array($file)){ //判断是否为多张图片,记得接收图片格式的时候要json_decode($img,true)转成数组
foreach ($file as $img){
$img_name[] = $this->uploadOne($img,$uploadPath,$picr); //图片上传
}
}else{
$img_name[] = $this->uploadOne($file,$uploadPath,$picr); //图片上传
}
return implode(',',$img_name); //返回图片路径,用,分割的字符串
}
function uploadOne($file,$uploadPath,$picr = '')
{
header('Content-type:text/html;charset=utf-8');
$base64_image_content = trim($file);
//正则匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
$type = $result[2];//图片后缀
$dateFile = date('Y-m-d', time()) . "/"; //创建目录
$new_file = $uploadPath.$dateFile;
if (!file_exists($new_file)) {
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($new_file, 0700,true);
}
$filename = time() . '_' . uniqid() . ".{$type}"; //文件名
$new_file = $new_file . $filename;
//写入操作
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
return $picr.$dateFile . $filename; //返回文件名及路径
} else {
throw new JsonErrorException('上传图片失败!');
}
}
}