tp5簡單的圖片上傳
阿新 • • 發佈:2019-01-08
這裡運用的是tp5的原始的圖片上傳功能如下:(1)增加了校驗器驗證圖片格式,如果有興趣的還可以新增大小等驗證。(2)圖片上傳後顯示圖片。(3)等待更新的功能:圖片上傳實時預覽,並將路徑存入資料庫。
一,建立index/controller/index.php控制器
<?php namespace app\index\controller; use think\Image; use think\Controller; class Index extends Controller { // 檔案上傳表單 public function index() { return $this->fetch(); } // 圖片上傳處理 public function picture() { // 獲取表單上傳檔案 例如上傳了001.jpg $file = request()->file('image'); //校驗器,判斷圖片格式是否正確 if (true !== $this->validate(['image' => $file], ['image' => 'require|image'])) { $this->error('請選擇影象檔案'); } else { // 移動到框架應用根目錄/public/uploads/ 目錄下 $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'); if ($info) { // 成功上傳後 獲取上傳資訊 //存入相對路徑/upload/日期/檔名 $data = DS . 'uploads' . DS . $info->getSaveName(); //模板變數賦值 $this->assign('image', $data); return $this->fetch('index'); } else { // 上傳失敗獲取錯誤資訊 echo $file->getError(); } } }
}
二,建立檢視檔案index/view/index.html
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>影象上傳和處理示例</title> <style> body { font-family:"Microsoft Yahei","Helvetica Neue",Helvetica,Arial,sans-serif; font-size:16px; padding:5px; } .form{ padding: 15px; font-size: 16px; } .form .text { padding: 3px; margin:2px 10px; width: 240px; height: 24px; line-height: 28px; border: 1px solid #D4D4D4; } .form select { padding: 5px; margin:2px 10px; width: 150px; height: 30px; line-height: 30px; border: 1px solid #D4D4D4; } .form .btn{ margin:6px; padding: 6px; width: 120px; font-size: 16px; border: 1px solid #D4D4D4; cursor: pointer; background:#eee; } .form .file{ margin:6px; padding: 6px; width: 220px; font-size: 16px; border: 1px solid #D4D4D4; cursor: pointer; background:#eee; } a{ color: #868686; cursor: pointer; } a:hover{ text-decoration: underline; } h2{ color: #4288ce; font-weight: 400; padding: 6px 0; margin: 6px 0 0; font-size: 28px; border-bottom: 1px solid #eee; } div{ margin:8px; } </style> </head> <body> <h2>影象上傳和處理示例</h2> <form method="post" enctype="multipart/form-data" class="form" action="{:url('picture')}"> 選擇影象檔案:<input type="file" class="file" name="image"><br/> <input type="submit" class="btn" value=" 提交 "> </form> <div style="width: 200px;height: 500px;"> <img src="{$image}"/> </div> </body> </html>
第三,建立上傳資料夾public/uploads