Html
<form
action="{{
URL::route('upload.files')}}"
method="post"
id="imgForm">
<input
type="file"
class="hide-avatar"
name="file">
<input
type="text"
class="file_import"
name="files"
value="">
<button
class="btn btn-secondary change-avatar"
type="button"
><i
class="fa fa-upload"></i>上传</button>
</form>
Css
/*导入文件上传*/
.hide-avatar{
display:none;
}
#imgForm{
display:inline;
}
.file_import{
display:none;
}
Javascript(使用前引用jquery.js,使用layer.js弹出提示)
<script>
$(function(){
//ajax 上传
$(document).ready(function()
{
//上传图片相关
$('.change-avatar').click(function()
{
$('.hide-avatar').click();
});
$('#imgForminput[name=file]').on('change',function(){
layer.load(0, {shade:[0.2,'#616161']});
$('#imgForm').ajaxForm({
url
: $(this).prop("action"),
post:"POST",
beforeSubmit:function(data){
$.each(data,function(i){});
},
headers:{
'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
},
success:function(data){
console.log(data);
layer.closeAll('loading');
if(data.status==
0){
layer.msg(data.msg,{time:1500},function(){
window.location.reload();
});
}else{
layer.msg(data.msg,{time:1500},function(){
$(".file_import").val(data.path);
});
}
},
dataType:'json'
}).submit();
});
});
})
</script>
Php
路由:
//后台导入上传
Route::post('/upload/files',[
'as'=>
'upload.files','uses'
=> 'UploadController@files',
]);
/*
@ Laravel框架
@ 上传文件
*/
public functionfiles(){
$file=
Input::file('file');
$clientName=
$file->
getClientOriginalName();
$allowed_extensions= ["xls"];
if($file->getClientOriginalExtension()
&& !in_array($file->getClientOriginalExtension(),$allowed_extensions))
{
$json['status']
= 0;
$json['msg']
= '请上传xls后缀格式文件';
}else{
$destinationPath=
'upload/eximport/'.date('Ymd').'/';
$extension=
$file->getClientOriginalExtension();
$fileName=
date('YmdHis').'.'.$extension;
$info=
$file->move($destinationPath,$fileName);
if($info){
$json['status']
= 1;
$json['msg']
= '上传成功';
$json['path']
= $destinationPath.$fileName;
}else{
$json['status']
= 0;
$json['msg']
= '上传失败';
}
}
return$json;
}