我的输入形式如下:
<?= $form->field($model, 'imageFile', ['inputOptions' => ['id' => 'Imageupload']])->hiddenInput()->label(false) ?>
fieldd将图片作为base64字符串,如下所示:
data:image/png;base64,iVBORw0K...
我的模型验证规则包含以下声明:
public function rules() {
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
但似乎这对base64字符串不起作用。 有没有办法在模型中验证它,或者我是否必须在控制器中生成一个真实的图像然后用各种PHP函数验证它?
答案 0 :(得分:1)
验证规则无法按预期工作,因为您的字段类型不是类型file
,而且您还将图像数据手动存储为base64
编码字符串。现在要解决您的问题,您可以通过使用下面给出的PHP代码手动检查文件类型。
$model->imageFile = "/9j/4AAQSkZJRgABAQEASABIA...";
$mimetype = getImageMimeType($model->imageFile);
echo $mimetype;
function getBytesFromHexString($hexdata) {
for ($count = 0; $count < strlen($hexdata); $count += 2)
$bytes[] = chr(hexdec(substr($hexdata, $count, 2)));
return implode($bytes);
}
function getImageMimeType($imageString) {
$imagedata = base64_decode($imageString);
$imagemimetypes = array(
"jpeg" => "FFD8",
"png" => "89504E470D0A1A0A",
"gif" => "474946",
"bmp" => "424D",
"tiff" => "4949",
"tiff" => "4D4D"
);
foreach ($imagemimetypes as $mime => $hexbytes) {
$bytes = getBytesFromHexString($hexbytes);
if (substr($imagedata, 0, strlen($bytes)) == $bytes)
return $mime;
}
return NULL;
}