上传视图
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传测试</title>
<link rel="stylesheet"
href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-10">
<form class="form-horizontal 8" role="form"
action="upload/uploadImage" method="post" name="article" enctype="multipart/form-data">
<div class="form-group">
<label for="title" class="col-md-2 control-label">文章标题</label>
<div class="col-md-8">
<input type="text" class="form-control" id="title" name="title" placeholder="请输入文章标题">
{{csrf_field()}}
</div>
</div>
<div class="form-group">
<label for="file" class="col-md-2 control-label">附件</label>
<div class="col-md-8">
<input type="file" class="form-control" id="file" name="file"/>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">新增</button>
<button type="reset" class="btn btn-default">取消</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
设置路由
<?php
Route::view('/upload','upload');
Route::post('/upload/uploadImage','UploadController@uploadImage');
上传文件验证控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UploadController extends Controller
{
public function toUpload(){
return view("upload.uploadImage");
}
public function uploadImage(Request $request){
if($request->hasFile('file')&&$request->file('file')->isValid()){
$file=$request->file('file');
$allowed_extensions = ["png", "jpg", "gif"];
if (!in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
dd('只能上传png,jpg和gif格式的图片.');
}else{
$destinationPath = 'uploads/';
$extension = $file->getClientOriginalExtension();
$fileName=md5(time().rand(1,1000)).'.'.$extension;
$file->move($destinationPath,$fileName);
$filePath = asset($destinationPath.$fileName);
return view('showpic',['picpath'=>$filePath]);
}
}else{
echo '图片上传失败请重试.';
}
}
public function uploadImage(Request $request){
$file=$_FILES["fname"];
if(!empty($_FILES) && $file['error']===0){
$type=$file[' type '];
if($type == 'image/gif' || $type == 'image/jpeg' || $type == 'image/png'){
$size= $file['size'];
if($size< 8*1024*1024){
$tmp_file=$file["tmp_name"];
$ext=pathinfo($file["name"],PATHINFO_EXTENSION);
$new_file="file".rand(1,1000000).".".$ext;
$path="uploads/";
$new_file=$path.$new_file;
move_uploaded_file($tmp_file,$new_file);
echo "上传成功";
}else{
echo "文件过大,无法上传";
}
}else{
echo "文件类型不正确";
}
}else{
echo "文件上传失败";
}
}
}
文件上传成功展示
<html>
<body>
<h1>上传的图片</h1>
<img src={{$picpath}}/>
</body>
</html>