1. 程式人生 > 程式設計 >TP5框架實現上傳多張圖片的方法分析

TP5框架實現上傳多張圖片的方法分析

本文例項講述了TP5框架實現上傳多張圖片的方法。分享給大家供大家參考,具體如下:

1、效果圖(每點選一次‘新增選項',就會有一個新的 file 框來新增新的圖片)

TP5框架實現上傳多張圖片的方法分析

2、view

<!--不要忘了引入jquery檔案-->
<!-- post傳值方式和檔案傳輸協議一定要加上 -->
<input type="file" name="image[]">
<input type="button" id="add" name="add" value="+ 新增選項">
<button type="submit" name="submit">新增</button>
 
<script type="text/javascript">
  $("#add").click(function(){
    $(this).before('<input type="file" name="image[]">');
  });
</script>

3、controller

//接收從view來的圖片陣列
$image=request()->file('image');
 
//例項化模型,並呼叫裡面的新增圖片的方法
$details = new Details();
$info = $details->add($image);
if($info === 1)
{
  return '操作成功';
}
else
{
  return '操作失敗';
}

4、model

//將接收到的 $image foreach遍歷新增
foreach($image as $image)
{
  //例項化模型
  $details = new Details();
  $time=date('Ymd',time());
  //將當前的時間戳定義為檔名
  $filename=time();
  //檢測是否存在存放圖片的資料夾
  if(!file_exists(ROOT_PATH . 'public' . DS .'static'. DS .'img'))
  {
    //建立檔案
    mkdir(ROOT_PATH . 'public' . DS .'static'. DS .'img');
  }
  //上傳圖片
  $info=$image->move(ROOT_PATH . 'public' . DS .'static'. DS .'img'.DS.$time,$filename);
  //將圖片路徑存放在資料庫中
  $details->url = $time.DS.$info->getFileName();
  $details->allowField(true)->save();
}
return 1;

5、over over over

更多關於thinkPHP相關內容感興趣的讀者可檢視本站專題:《ThinkPHP入門教程》、《thinkPHP模板操作技巧總結》、《ThinkPHP常用方法總結》、《codeigniter入門教程》、《CI(CodeIgniter)框架進階教程》、《Zend FrameWork框架入門教程》及《PHP模板技術總結》。

希望本文所述對大家基於ThinkPHP框架的PHP程式設計有所幫助。