项目中使用的图片上传方法,base64存本地

 //生成健康报告
public function uploadJkbg(Request $r) {
$data = $r->all();
$jkbg['jkbg_ctime'] = time();
$jkbg['jkbg_aid'] = \Auth::user()->id;
$jkbg['jkbg_id'] = str_random(6) . mt_rand(100000, 999999);
//演示数据
// $data['jkbg_pic'] = array(0=>$base64);
//上传图片到服务器 返回路径
if(!empty($data['jkbg_pic'])){
$pic_arr = $this->uploadBaseIma($data['jkbg_pic']); //这一步把图片存入 参数是图片base64 数组格式
}else{
$pic_arr = array();
}
$jkbg['jkbg_pic'] = json_encode($pic_arr);
//添加报告
\DB::beginTransaction();
$result = \DB::table('dxjk_jkbg')->insert($jkbg);
if(!$result){
\DB::rollback();
\DB::commit();
return ['code' => 1001, 'data' => ['message' => '上传报告失败']];
}
//修改上传状态
$ress = \DB::table('dxjk_admin')->where('id',$jkbg['jkbg_aid'])->update(['admin_status' => 3]);
\DB::commit();
return ['code' => 1000, 'data' => ['message' => '上传报告成功']];

}
//处理图片信息 返回对应的路径
public function uploadBaseIma($imgArr){
$result = array();
//将路径直接设置在uploads下
if($imgArr){
foreach($imgArr as $k => $v){
if($v){
$address = $this->baseChangeImg($v);
$result[$k] = $address;
}else {
return array();
}
}
return $result;
}
}

//base64转化为本地图片
public function baseChangeImg($base)
{
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base, $result)) {
$type = $result[2];
$path = '/base' . date('Ymd', time()) . "/";
$new_file = public_path('uploads') . $path;
if (!file_exists($new_file)) {
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($new_file, 0700);
}
$name = uniqid() . ".{$type}";
$new_file = $new_file . $name;
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base)))) {
return $path . $name;
} else {
return false;
}
}
}
posted @ 2018-08-13 10:58  LvFish  阅读(1058)  评论(0编辑  收藏  举报