ThinkPHP6接收图片base64进行文件上传。

解决场景: 前端生成一个canvas图片后,传给后端是一串图片的base64字符串,常规的文件上传无法获取到这个文件。

于是,将base64保存到临时文件夹后,再转成一个thinkphp6上传文件类的对象,模拟上传文件。


$name = 'file';
// 优先从请求中获取的上传文件
$this->file = Request::file($name);

// 如果请求中没有获取文件流, 尝试在表单中获取同等的base64
if (empty($this->file)) {
$str = Request::post($name);
$result = img_base64_2_binary($str, public_path('temp'));
$result !== false && $this->file = new \think\file\UploadedFile($result, basename($result));
// 此时 $this->file 相当于一个从请求中获取的上传文件, 可以进行文件的大小后缀校验等等
}



if (!function_exists('img_base64_2_binary')) {
/**
* @Description 图片base64转成二进制流
* @param string $str base64
* @param string $save_path 保存目录 / 结尾
* @return false|string
*/
function img_base64_2_binary(string $str, string $save_path = '') {
$result = false;
$pregInfo = preg_match('/^(data:\s*image\/(\w+);base64,)/', $str, $photoInfo);
if ($pregInfo !== false) {
$clearBase64HeadWithPhoto = str_replace(array($photoInfo[1], ' '), array('', '+'), $str);
$photoFileSource = base64_decode($clearBase64HeadWithPhoto);
$result = $photoFileSource;

if ($save_path) {
$filePath = $save_path . rand(100, 999) . uniqid() . '.' . $photoInfo[2];
/* 写文件 */
file_put_contents($filePath, $result);
return $filePath;
}

}
return $result;
}
}