联系官方销售客服
1835022288
028-61286886
layui文件上传组件配合后台代码进行文件上传
html部分代码
<div style="margin-left: 110px;text-align: center;" class="layui-upload"> <input type="hidden" name="head[0]" lay-verify="head" id="head" value=""> //这里是文件上传字段对应的name值, 完成上传之后,要把返回的id赋值给value <button type="button" class="layui-btn" id="upload"> <i class="layui-icon"></i> 文件上传 </button> <div class="layui-upload-list"> <img style="width: 140px; height: 180px; border: 0.5px solid " class="layui-upload-img" id="imgUpload"> <p id="demoText"></p> </div> </div>
js部分代码
layui.use('upload', function(){ var $ = layui.jquery ,upload = layui.upload; var uploadInst = upload.render({ elem: '#upload'+n, url: '/admin.php?s=census&c=home&m=upload', field: "file_data", data: { file_data: function(){ return $('#upload'+n).val(); }, {csrf_token()} : "{csrf_hash()}" }, before: function(obj){ //预读本地文件示例,不支持ie8 obj.preview(function(index, file, result){ $('#imgUpload'+n).attr('src', result); //图片链接(base64) }); }, done: function(res){ if (!res.id){ return layer.msg('<span style="color: #fff">'+res.msg+'</span>'); }else { if(res.code == 1){ $("#head"+n).attr("value", res.id); //这里是上传完成之后,将文件返回的id赋值给了head字段对应的表单的value return layer.msg('<span style="color: #fff">上传成功</span>'); }else{ return layer.msg('<span style="color: #fff">上传失败,请重试!</span>'); } } }, error: function(){ //请求异常回调 } });
php部分代码
public function upload() { $files = $this->request->getFiles(); $p['exts'] = $files['file_data']->getClientExtension(); $p['size'] = 100; // 验证上传权限 $rt = \Phpcmf\Service::L('upload')->upload_file([ 'path' => '', 'form_name' => 'file_data', 'file_exts' => @explode(',', $p['exts']), 'file_size' => (int)$p['size'] * 1024 * 1024, 'attachment' => \Phpcmf\Service::M('Attachment')->get_attach_info(), ]); if (!$rt['code']) { exit(dr_array2string($rt)); } // 附件归档 $data = \Phpcmf\Service::M('Attachment')->save_data($rt['data']); if (!$data['code']) { exit(dr_array2string($data)); } // 上传成功 if (IS_API_HTTP) { $data['data'] = [ 'id' => $data['code'], 'url' => $rt['data']['url'], ]; exit(dr_array2string($data)); } else { exit(dr_array2string(['code' => 1, 'msg' => dr_lang('上传成功'), 'id' => $data['code'], 'info' => $rt['data']])); } }
进来学习的,学习一下