success('请求成功'); } public function uploads() { // 获取base64 $img = $this->request->post('base64img'); if(!$img){ $this->error('参数缺失!'); } //获取base64中图片数据 $url = explode(',', $img); if(!isset($url[1])){ $this->error('参数有误!!'); } //$img = str_replace(' ', '+', $img); $data = base64_decode($url[1]); if ($url[1] != base64_encode(base64_decode($url[1]))) { $this->error('参数有误!'); } $file_name = md5(microtime(true));// 图片名称 $this->createDir(ROOT_PATH . 'public/uploads/'.date("Ymd") ."/"); $path = ROOT_PATH . 'public/uploads/'.date("Ymd") ."/". $file_name. '.png'; // 图片保存路径 //$url = 'http://xxx.xx.xxx/uploads/'. date("Ymd") ."/" . $file_name . '.png'; // 用于访问图片的地址 $r = file_put_contents($path, $data);// 生成图片 if (!$r) { $this->error("上传失败"); }else{ return $this->success(__('Uploaded successful'), ['url' => 'uploads/'.date("Ymd") ."/". $file_name. '.png']); } } public function createDir($dir) { if (!is_dir ($dir )) { mkdir($dir, 0777, true); chmod($dir, 0777); } } /** * 上传文件 * @ApiMethod (POST) * @param File $file 文件流 */ public function upload() { Config::set('default_return_type', 'json'); //必须设定cdnurl为空,否则cdnurl函数计算错误 Config::set('upload.cdnurl', ''); $chunkid = $this->request->post("chunkid"); if ($chunkid) { if (!Config::get('upload.chunking')) { $this->error(__('Chunk file disabled')); } $action = $this->request->post("action"); $chunkindex = $this->request->post("chunkindex/d"); $chunkcount = $this->request->post("chunkcount/d"); $filename = $this->request->post("filename"); $method = $this->request->method(true); if ($action == 'merge') { $attachment = null; //合并分片文件 try { $upload = new Upload(); $attachment = $upload->merge($chunkid, $chunkcount, $filename); } catch (UploadException $e) { $this->error($e->getMessage()); } $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]); } elseif ($method == 'clean') { //删除冗余的分片文件 try { $upload = new Upload(); $upload->clean($chunkid); } catch (UploadException $e) { $this->error($e->getMessage()); } $this->success(); } else { //上传分片文件 //默认普通上传文件 $file = $this->request->file('file'); try { $upload = new Upload($file); $upload->chunk($chunkid, $chunkindex, $chunkcount); } catch (UploadException $e) { $this->error($e->getMessage()); } $this->success(); } } else { $attachment = null; //默认普通上传文件 $file = $this->request->file('file'); //var_dump($file);die(); try { $upload = new Upload($file); $attachment = $upload->upload(); } catch (UploadException $e) { $this->error($e->getMessage()); } $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]); } } }