對laravel-admin的圖片上傳機制有深深的疑惑,在用戶信息頁面上刪除頭像圖片就會報錯,當時用的是1.4的,后來更新1.5 發(fā)現(xiàn)刪除按鈕直接消失了,在使用過程中,要是在form中正常使用image就好用,稍微寫的復雜一點(比如我把$form->image寫在tab里的時候)就不好用了。
?php
namespace App\Admin\Controllers;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Form\Field\File;
use Illuminate\Http\UploadedFile;
class FileController extends Controller
{
use ModelForm;
public function index($type,$file=null,$ajax=true,$file_name="")
{
$file = $file ? $file : $_FILES['img'];
if($file['error']!=0){
$data = array('status'=>false,'msg'=>trans('admin::lang.Upload_error'));
return $ajax ? json_encode($data) : $data;
}
//得到文件名稱
$name = $file['name'];
$img_type = strtolower(substr($name,strrpos($name,'.')+1)); //得到文件類型,并且都轉化成小寫
$allow_type = array('jpg','jpeg','gif','png'); //定義允許上傳的類型
//判斷文件類型是否被允許上傳
if(!in_array($img_type, $allow_type)){
$data = array('status'=>false,'msg'=>trans('admin::lang.imgtype_error').$img_type);
return $ajax ? json_encode($data) : $data;
}
//判斷是否是通過HTTP POST上傳的
if(!is_uploaded_file($file['tmp_name'])){
$data = array('status'=>false,'msg'=>trans('admin::lang.post_img'));
return $ajax ? json_encode($data) : $data;
}
$file_name = $file_name ? $file_name.'.'.$img_type : md5(uniqid()).Carbon::now()->timestamp.'.'.$img_type;
if($type=='attr_img'){
$upload_path = public_path().'/upload/goods/attr_img/'; //上傳文件的存放路徑
$path = "goods/attr_img/";
}elseif($type=='goods'){
$upload_path = public_path().'/upload/goods/'; //上傳文件的存放路徑
$path = "goods/";
}else{
$upload_path = public_path().'/upload/'.$type.'/'; //上傳文件的存放路徑
$path = $type."/";
}
if(!is_dir($upload_path)){
@mkdir($upload_path);
}
//開始移動文件到相應的文件夾
if(move_uploaded_file($file['tmp_name'],$upload_path.$file_name)){
$data['status'] = true;
$data['path'] = $path.$file_name;
$data['view_path'] = config('admin.upload.host').$path.$file_name;
}else{
$data = array('status'=>false,'msg'=>trans('admin::lang.moveimg_error'));
return $ajax ? json_encode($data) : $data;
}
if($ajax){
return json_encode($data);
}else{
return $data;
}
}
public function multipleImg($type,$files,$ajax=true){
$imgs = array('status'=>true);
for($i=0;$icount($files['name']);$i++){
$file['name'] = $files['name'][$i];
$file['type'] = $files['type'][$i];
$file['tmp_name'] = $files['tmp_name'][$i];
$file['error'] = $files['error'][$i];
$file['size'] = $files['size'][$i];
$data = $this->index($type,$file,false);
if($data['status']){
$imgs['path'][$i] = $data['path'];
$imgs['view_path'][$i] = $data['view_path'];
}else{
return $ajax ? json_encode(array('status'=>false,'msg'=>$data['msg'])) : array('status'=>false,'msg'=>$data['msg']);
}
}
return $ajax ? json_encode($imgs) : $imgs;
}
}
public function deleteUrl($img){
$mconfig = MConfigModel::where('img',$img)->first();
$path = config('admin.upload.host').$mconfig->val;
if(file_exists($path)){
@unlink ($path);
}
$mconfig->val = "";
$mconfig->save();
return array('status'=>true);
}