//图片二进制流保存图片 public function writePdf(Request $request) { try { date_default_timezone_set('PRC'); $imgdata = $request->get('image'); $imgdata = substr(strstr($imgdata,','),1);//关键在于这句代码 if(empty($imgdata)){ return array('msg'=>'fail','data'=>'数据为空 请稍候重试'); } $base64 = base64_decode($imgdata); //$imgname = md5(time().rand(10000,99999).$this->uid); $path = $this->uid.'/'.$report_id.'/'.$cate_id.'/'.$industry_type; chdir(DIR_UPLOAD); mkdir_recursively($path);//递归创建目录 $imgtype = '.png'; $image_file_name = $name.$imgtype; $img_url = DIR_UPLOAD.$path.'/'.$image_file_name; //如果是修改的话先获取之前的图片然后删除之前的图片 if ($is_create == 2){ $image_info = DB::table('image')->select('image')->where('uid', $this->uid) ->where('report_id', $report_id)->where('cate_id', $cate_id)->where('industry_type', $industry_type)->first(); if ($image_info){ //删除之前的图片并情况库里的记录 unlink($image_info->image); DB::table("image")->where('uid', $this->uid)->where('report_id', $report_id)->where('cate_id', $cate_id)->where('industry_type', $industry_type)->delete(); } } $success = file_put_contents($img_url, $base64,true); $data = array(); if ($success){ //入库: $insertData = [ 'uid' => $this->uid, 'report_id' => $report_id, 'cate_id' => $cate_id, 'industry_type' => $industry_type, 'name' => $name, 'is_create' => $is_create, 'image' => $img_url, 'create_time' => date('Y-m-d H:i:s'), ]; DB::table('image')->insert($insertData); $data['code'] = 200; $data['success']= 'true'; $data['image_path']= $img_url; $this->successInfo['data'] = $data; return $this->successInfo; }else{ $data['code'] = 505; $data['success']= 'fail'; $data['msg']='保存失败,请联系管理员'; $this->successInfo['data'] = $data; return $this->successInfo; } } catch (Exception $e) { return echoErrorInfo($e->getCode(), $e->getMessage()); } }
define('DIR_UPLOAD', dirname(realpath(__DIR__)).'/'.'public/upload/images/');
/** * 递归创建文件夹 * @param $path * @return bool */ function mkdir_recursively($path) { $path = str_replace('/', '/', rtrim($path, '/')); $pathArr = explode('/', $path); if ($pathArr[0] == "") { chdir('/'); array_shift($pathArr); } try { foreach ($pathArr as $eachPath) { if (!is_dir($eachPath)) { mkdir($eachPath); } chdir($eachPath); } } catch (Exception $e) { \Log::info($e->getMessage()); \Log::info($e->getMessage()); return false; } return true; }