HTML代码:
<form id="formFile" accept-charset="UTF-8" method="post" action="/api/xxxx" enctype="multipart/form-data">
<span class="marketing-label">文件上传*</span>
<input type="file" name="inputfile"
{{ csrf_field() }}
<button class="marketing-button" name="button" onclick="Sub();return false;">上传</button>
</form>
<script>
function Sub()
{
//这里注意,一定要用document.getElementById('formFile') 不要用Jquery $
var formData = new FormData(document.getElementById('formFile'));
//可扩展其他参数
formData.append("other_filed",123);
console.log(formData);
$.ajax({
url: '/api/xxx',
type: 'POST',
data: formData, // 上传formdata封装的数据
cache: false, // 不缓存
processData: false, // jQuery不要去处理发送的数据
contentType: false, // jQuery不要去设置Content-Type请求头
success:function (data) { //成功回调
console.log(data);
}
});
}
</script>
后端代码:
public function xxx()
{
$all = $this->_request->input();
$file = $this->_request->file('inputfile');
//随机名称+获取客户的原始名称
$ext = $file->getClientOriginalExtension();
$path = $file->getRealPath();
//验证图片类型,大小等
$save_name = date('YmdHis',time()) .'-' . uniqid() . '.' . $ext;
//保存图片
//注意 文件过大 会触发TokenMismatchException 需要修改php.ini 最大上传值
$bool = Storage::disk('uploads')->put($save_name, file_get_contents($path));
if ($bool)
{
$data = \Excel::load("uploads/" . $save_name, function ($reader) {}, 'GBK')->get();
$data = $data->toArray();
if (count($data) > 0)
{
var_dump($data);
}
else
{
echo 'read file fail';
}
}
else
{
echo 'upload fail';
}
}