1.编辑html
<form action="{{route('user-admin.category.import')}}" style="display: inline;" id="upload-form" method="post" enctype="multipart/form-data">
{{--csrf验证开始--}}
@csrf
{{--csrf验证结束--}}
{{--multiple 就可以多文件上传 name 后面加[]--}}
<input type="file" name="excel" id="fileupload" style="display:none" />
<a href='#' onclick="document.getElementById('fileupload').click();return false;" class="badge badge-primary r-3 ">
批量导入
</a>
</form>
2.JavaScript 脚本
<script>
/**
* 文件上传的方法
*/
$("#fileupload").on("change",function(){
document.getElementById('upload-form').submit();
})
</script>
3.laravel php `config/filesystems.php` 编辑配置文件,添加uploads
<?php
.
.
.
'disks' => [
// 本地端的local空间
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
// 本地端的public空间
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'visibility' => 'public',
],
// 新建一个本地端uploads空间(目录) 用于存储上传的文件
'uploads' => [
'driver' => 'local',
// 文件将上传到storage/app/uploads目录
'root' => storage_path('app/uploads'),
// 文件将上传到public/uploads目录 如果需要浏览器直接访问 请设置成这个
//'root' => public_path('uploads'),
],
// Amazon S3 相关配置
's3' => [
'driver' => 's3',
'key' => 'your-key',
'secret' => 'your-secret',
'region' => 'your-region',
'bucket' => 'your-bucket',
],
],
];
在controller编辑代码
.
.
.
use Illuminate\Support\Facades\Storage;
.
.
.
public function import(Request $request)
{
$file = $request->file('excel');
if ($file->isValid()) {
$originalName = $file->getClientOriginalName(); #文件原名
$type = $file->getClientMimeType(); #获取文件类型
$ext = $file->getClientOriginalExtension(); #扩展名
$realPath = $file->getRealPath(); #临时文件的绝对路径
$fileName = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext; #定义新文件名称
$bool = Storage::disk('uploads')->put($fileName, file_get_contents($realPath));
}
}
.
.
.