多圖片|單圖片上傳(tp5)
前言
相對於tp3,tp5的圖片上傳越發方便,可能只需要短短几行代碼,就可以實現。
第一步 在控制器中把獲取到的file調用move方法
//修改輪播
public function add()
{
if(Request()->isGet()){
$id = input("id");
$list = db("banner")->where("id",$id)->find();
$img = explode(',', $list['img']);
$type = db('banner_type')->select();
return view('',['list'=>$list,'type'=>$type,'img'=>$img]);
}
if(Request()->isPost()){
//獲取數組
$data = input("post.");
$data['update_time'] = time();
// 接收多圖文件
$file=Request()->file("files");
if($file!=null){ //在不爲空的情況下對數據進行遍歷
foreach ($file as $k => $v) {
$info = $v->move(ROOT_PATH . 'public' . DS . 'uploads'); //對每個文件進行上傳
$img[] ='/uploads/'.str_replace("\\","/",$info->getSaveName()); //獲取其路徑
}
$data['imgs'] = implode(',', $img); //將多個圖片路徑數據轉換爲字符串。
//接收單圖文件
$pic= Request()->file("pic");
if($pic!=null){ //在不爲空的情況下執行
$info1 = $pic->move(ROOT_PATH . 'public' . DS . 'uploads'); //對文件進行上傳
$pic[] ='/uploads/'.str_replace("\\","/",$info1->getSaveName()); //獲取其路徑
$data['pic'] = implode(',', $pic); //將圖片路徑數據轉換爲字符串。
}
$res = db("banner")->where("id",$data['id'])->update($data); //修改
if($res){
$this->success('修改成功',url('index'));
}else{
$this->error('修改失敗');
}
}
}
在tp5中單圖跟多圖也就少了一層遍歷而已。
$file=Request()->file("files");
if($file!=null){
foreach ($file as $k => $v) {
$info = $v->move(ROOT_PATH . 'public' . DS . 'uploads');
$img[] ='/uploads/'.str_replace("\\","/",$info->getSaveName());
}
$data['img'] = implode(',', $img);
}