laravel jquery ajax 提交文件类型表单
//html 表单
<div class="tab-content"> <form class="batch_form" id="new_batch_form" action="{{route("products_batch_submit")}}" accept-charset="UTF-8" method="post" enctype="multipart/form-data"> @csrf <div class="gd_add"> <p>EXCEL请输入产品的CAS号和英文产品名称,<a href="/static/new/excel/批量新增商品.xlsx" class="red" style="font-size: 16px;margin-left: 20px;">示例下载</a></p> <div> <input type="file" name="file" id="batch_goods"> </div> <div class="add_btn"> <a href="javascript:void(0);" class="blue btn submitBtn" id="publish_product_btn">立即新增</a></div> </div> </form> </div>
//jquery
$("#publish_product_btn").click(function () { var file = $("#batch_goods").val(); var exec = (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : ''; if(!file){ alert_message('提示','请选择上传EXCEL文件!',null,function(){ close_alert_div(); }) return false; } if (exec != "xlsx" && exec != "xls") { alert_message('提示','文件格式不对,请上传Excel文件!',null,function(){ close_alert_div(); }) return false; } $('body').append(loading); var formData = new FormData($("#new_batch_form")[0]);; $.ajax({ url: $("#new_batch_form").attr('action'), //data:$("#new_batch_form").serializeArray(), type: 'post', cache: false, dataType: 'json', data: formData, contentType: false, processData: false, success: function (data) { close_loading_div(); if(data.data.code == "SUCCESS"){ close_alert_div(); alert_message('提示', data.msg, '500px', function () { window.location.href="{{route("products_batch_add")}}"; }); }else{ alert_message('提示', data.msg, '500px', function () { close_alert_div(); }); return false; } }, error: function () { close_loading_div(); alert_message('提示','系统异常,请联系客服人员!',null,function(){ close_alert_div(); }) } }) });
//laravel 后台
public function products_batch_submit(Request $request){ if(!$request->hasFile('file')){ exit('上传文件为空!'); } $file = $request->file('file'); //原文件名 //$originalName = $file->getClientOriginalName(); //后缀 $fileExtension = $file->getClientOriginalExtension(); if(! in_array($fileExtension, ['xls', 'xlsx'])) { return false; } //临时绝对路径 $filePath = $file->getRealPath(); $filename = date('Ymdhis').mt_rand(10,99).'.'.$fileExtension; Storage::disk('public')->put($filename, file_get_contents($filePath)); $filePath = storage_path("app/public/".$filename); //$filename = "2019-12-23-02-04-31.xls"; //$filePath = storage_path("app/public/".$filename); Excel::import(new GoodsImport, $filePath); Storage::disk('public')->delete($filename); return Y::success('上传成功!',["code"=>"SUCCESS"]); }