上传文件路由
//web.php
Route::post('upload' , 'UploadController@store')->name('upload');
upLoadImg.blade.php 模板文件
//_upload.blade.php
@php
$value = isset($value)?$value:asset('assets/images/avatar.jpg');
$name = isset($name)?$name:'image';
@endphp
<div class="form-group row">
<label for="{{ $name }}" class="col-sm-3 col-form-label">图标</label>
<div class="col-sm-9">
<button type="button" class="layui-btn" id="{{ $name }}">
<i class="layui-icon"></i>上传图片
</button>
</div>
</div>
{{--显示图片区域--}}
<div class="form-group row">
<div class="offset-3 col-sm-9">
<img id="{{ $name }}-show" src="{{ $value }}" alt="{{ $value }}" width="100" height="100"
class="img-circle border-dark" style="border:1px solid rgba(128,128,128,0.2);">
</div>
</div>
{{--图片表单区域--}}
<input type="hidden" name="{{ $name }}" value="{{ $value }}">
<script>
layui.use(['upload', 'layer'], function () {
var upload = layui.upload
, layer = layui.layer;
//执行实例
var uploadInst = upload.render({
elem: '#{{ $name }}' //绑定元素
// , headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}//若没有排除post上传图片的令牌验证,就需要将此处取消注释
, url: '/upload' //上传接口
, field: '{{ $name }}'
, done: function (res) {
//上传完毕回调
console.log(res)
if (res.code == 0) {
$('#{{ $name }}-show').attr('src', res.data.src);
$('input[name="{{ $name }}"]').attr('value',res.data.src)
}
}
, error: function () {
//请求异常回调
console.log('error')
layer.msg('上传图片错误');
}
});
})
</script>
UploadController.php
//uploadController.php
.
.
.
public function store(Request $request)
{
//todo 多文件上传未设置
$files = $request->allFiles();
if(is_array($files)){
foreach($files as $file){
$path = Storage::putFile('public' , $file);
}
}
if( $path ) {
return json_encode(['code' => 0 , 'msg' => '上传成功' , 'data' => ['src' => '/storage/' . str_replace('public/' , '' , $path)]]);
}
else {
return json_encode(['code' => 1 , 'msg' => '上传失败']);
}
}
//create.blade.php
@include('xxx/upload.blade.php',['name'='img','value'=>$model->img)//在需要引用的位置,加入此段代码即可,需要先引入layui.css和layui.js,编辑页面设置value值,创建页面不需要value值
排除上传令牌验证
image.png
效果
image.png
image.png
网友评论