ThinkPhp5 图片上传实例
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文章添加</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<h3>文章添加</h3>
<form action="save" method="post" enctype="multipart/form-data">
文章标题:<input type="text" name="title" value=""><br/><br/>
文章描述:<input type="text" name="description" value=""><br/><br/>
文章封面:<input type="file" name="image_url" /> <br><br>
<button type="submit">提交</button><br><br>
</form>
<img src="" class="img" width="300">
<script type="text/javascript">
$("input[name='image_url']").change(function(){
$(".img").attr("src",URL.createObjectURL($(this)[0].files[0]));
});
</script>
</body>
</html>
样例会在选择图片后可在下方预览图片 ,效果如下:
路由
Route::resource('article', 'article/index');
控制器
<?php
namespace app\admin\controller;
use think\facade\Request;
//use think\Request;
use think\Controller;
use think\DB;
class Article extends Controller
{
/**
* 保存新建的资源
*
* @param \think\Request $request
* @return \think\Response
*/
public function save(Request $request)
{
$file = request()->file('image_url');
$info = $file->move( '../public/uploads/image');
if($info){
// 成功上传后 获取上传信息
$_POST['image_url'] = '/uploads/image/'.$info->getSaveName();
$row = DB::name('article')->insert($_POST);
if($row){
return "<script>alert('添加成功');window.location.href='index?cancel=yes';</script>";
}
}else{
// 上传失败获取错误信息
echo $file->getError();
}
}
}