文件上传
在控制器中调用文件上传代码
use App\Http\Controllers\Controller;
use App\Service\Image;
public function uploadimage(){
$UploadImg = new Image();
$response = $UploadImg->Upload($this->request,'file');
return $response;
}
上传文件
public function Upload($request,$filename){
//检查上传文件中是否包含文件
if ($request->hasFile($filename)) {
//获取上传文件内容
$file = $request->file($filename);
//获取文件尾缀
$extension = $file->extension();
if($extension == "jpg" || $extension == "jpeg" || $extension == "png"){
//文件上传位置
$path = $file->store('category');
return json_box('SUCCESS',200,'上传成功',$path);
}
return json_box('FAIL',201,'文件格式不正确');
}
return json_box('FAIL',400,'上传文件不存在');;
}
文件存储在项目根目录下 storage\app
文件读取
在路由文件中新增加获取图片文件的路由
Route::get('/getimage/{one?}/{two?}/{three?}/{four?}/{five?}/{six?}/{seven?}/{eight?}/{nine?}',function(){
\App\Service\Image::imageStorageRoute();
});
//这里使用了闭包函数
路由指向的方法
static public function imageStorageRoute(){
//获取当前的url
$realpath = str_replace('getimage/','',Request::path());
$path = storage_path() ."/". $realpath;
//查看目录下是否存在文件
if(!file_exists($path)){
//报404错误
header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found");
exit;
}
//输出图片
header('Content-type: image/jpg');
echo file_get_contents($path);
exit;
}
然后就可以在页面中通过路由进行访问图片了
<div class="layui-card-body"><img src="/getimage/app/{{ $data->thumbnail }}" width="100" height="100"></div>