上传附件(图片base64)封装方法
项目中封装的接口:
public function error($msg){
header("Content-type: application/json");
$o['time'] = "".time();
$o['code'] = '1';
$o['errorMsg'] = $msg;
echo json_encode($o);
die;
}
public function Attachment(){
$d = array_merge($_POST,$_GET);
if( empty($d['attachment']) ) $this->error("附件不能为空");
//匹配出图片的格式
if (!preg_match('/^(data:\s*image\/(\w+);base64,)/', $d['attachment'], $result)) $this->error('格式错误!');
$type = $result[2];
$attachment = $d['attachment'];
$filename = date('His') . strtolower( base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, 10));
$imgurl = "upload/";
$imgurl = imgurl . $filename . "." . $type;
file_put_contents($imgurl, base64_decode(str_replace($result[1], '', $attachment)));
return $imgurl;
}