laravel ajax 异步表单上传文件和附件
<div> <form id="coa_form_@{{d.id}}" action="{{route("admin.company.upload_coa")}}" accept-charset="UTF-8" method="post"> @csrf <input type="hidden" name="company_id" value="@{{d.id}}"> <input type="hidden" name="cas" value="{{$inquiries->prod->cas}}"> <input type="file" id="upload@{{d.id}}" name="coa_file" rel="@{{d.id}}" value=""> </form> </div>
<script> layui.use(['layer','table','form','element','upload'],function () { var $ = layui.jquery; var layer = layui.layer; var form = layui.form; var table = layui.table; var element = layui.element; var upload = layui.upload; if (layEvent === 'upload'){ var rel = $(this).attr('rel'); var file_dom = 'upload'+rel; var coa_form = 'coa_form_'+rel; if($("#"+file_dom).val() == ''){ layer.msg('请上传附件', {icon: 5,time:1500}); return; } var formData = new FormData($("#"+coa_form)[0]); $.ajax({ url: $("#"+coa_form).attr('action'), data: formData, type: 'post', cache: false, contentType: false, processData: false, success: function (data) { layer.msg(data.msg, { icon: 1, time: 1500 //1秒关闭(如果不配置,默认是3秒) }, function(){ //window.location.reload(); table.reload('dataTable', { where: { company_info: $("#search_company_info").val(), } ,page:obj.curr }); }); }, error: function () { layer.msg('系统异常,请联系客服人员!', {icon: 5,time:1500}); return; } }); } }); </script>
服务端处理
public function upload_coa(Request $request){ $data['cas'] = $request->get('cas'); $data['company_id'] = $request->get('company_id'); $manage_id = isset(auth('web')->user()->id) ?auth('web')->user()->id : 0; $manage_name = isset(auth('web')->user()->name) ?auth('web')->user()->name : ''; //不为空 if($request->hasFile('coa_file')){ $file = $request->file('coa_file'); $fileExtension = $file->getClientOriginalExtension(); if(! in_array($fileExtension, ['jpg', 'png','jpeg','gif','pdf','doc','docx','csv','xls','xlsx'])) { return false; } $data['file_original_name'] = $file->getClientOriginalName(); $data['file_size'] = $file->getClientSize(); $data['file_suffix'] = $fileExtension; //临时绝对路径 $filePath = $file->getRealPath(); $filename = date('Ymdhis').mt_rand(1000,9999).'.'.$fileExtension; Storage::disk('coa')->put($filename, file_get_contents($filePath)); $data['file_name'] = $filename; $data['file_path'] = '/storage/coa/'.$filename; $data['url'] = config('app.url').$data['file_path']; $data['status'] = 1; $data['manage_id'] = $manage_id; $data['manage_name'] = $manage_name; } if(Coa::create($data)){ return Y::success('上传coa成功!'); }else{ return Y::error('上传coa失败!'); } }