作者:陈业贵 华为云享专家 51cto(专家博主 明日之星 TOP红人) 阿里云专家博主
第一步:在public目录下新建uploads目录
第二步:routes/web.php下复制粘贴
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;
use App\Http\Controllers\UserController;//路由文件里面引入控制器,不然无法实现哦
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::post('upload',[UserController::class,'upload']);
//控制器user。方法upload可以在浏览器上面写upload就行
Route::post('uploads',[UserController::class,'uploads']);
控制器user。方法uploads可以在浏览器上面写uploads就行
第三步:
config/filesystems.php/disks下(复制粘贴)uploads是要存的目录
'uploads'=>[
'driver'=>'local',
'root'=>public_path('uploads/'),
],
第四步:
app/Http/Middleware/VerifyCsrfToken.php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
"http://admin.tp5.com/index.php/uploads",//写这两个链接在这里csrf就不拦截
"http://admin.tp5.com/index.php/upload",
];
}
UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\View;
use Illuminate\Http\Request;
use App\Models\User\Teacher;
use Illuminate\Support\Facades\DB;
use Captcha;
use Illuminate\Support\Arr;
use Cache;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
class UserController extends Controller
{
//单文件上传
public function Upload(Request $request)
{
if ($request->isMethod('post')) {
$file = $request->file('file');//接收到文件
if($file->isValid()){//检测上传的文件是否合法,返回值为 true 或 false
$path = Storage::disk('uploads')->putFile(date('Ymd') , $file);
//保存路径:public/uploads/时间目录下
if($path) {
return ['code' => 0 , 'msg' => '上传成功' , 'data' => $path];//输出
}
else {
return ['code' => 400 , 'msg' => '上传失败'];
}
}
} else {
return ['code' => 400, 'msg' => '非法请求'];
}
}
public function Uploads(Request $request)
{
$path=[];
if ($request->isMethod('post')) {//检测是不是post方法上传的
$files = $request->file('files');//获取到上传很多文件
if(is_array($files)){//看是不是数组形式的
foreach($files as $file){//遍历数组。保存进public/uploads/时间目录下
$path = Storage::disk('uploads')->putFile(date('Ymd') , $file);
}
if( $path ) {
return ['code' => 0 , 'msg' => '上传成功' , 'data' => $path];
}
else {
return ['code' => 400 , 'msg' => '上传失败'];
}
}
}else{
return ['code' => 400, 'msg' => '非法请求'];
}
}
}
多文件上传:测试
单文件上传测试: