Lavarel文件上传

龙晟睿
2023-12-01

form表单提交

前端代码

<div class="flex-center position-ref full-height">
    <form method="POST" action="{{URL('/weChat/upload')}}" enctype="multipart/form-data">
        <input type="file" name="myfile" />
        <input type="submit" name="submit" value="Submit" />
    </form>
</div>

action里的“/weChat/upload”,在routes/web.php文件中配置:
Route::post(‘/weChat/upload’,’Admin\NoticesController@upLoad’)

后端代码

//上传文件
    public function upLoad(Request $request){
        //上传文件到服务器,放到临时文件夹中
        $file = Input::file('document');
        //获取文件名称
        $clientName = $file -> getClientOriginalName();
        //获取文件后缀
        $entension = $file -> getClientOriginalExtension();
        //生成新的文件名称
        $newName = md5(date("Y-m-d H:i:s").$clientName).".".$entension;
        //把文件从临时文件中移到storage/uploads文件夹下
        $path = $file -> move('storage/uploads',$newName);
        //存库
        $data['file_name'] = $clientName;
        $data['path'] = $path;
        if (Notice::where('id',$request->id)->update($data)){
            return ResponseLayout::apply(true,'','上传成功');
        }else{
            return ResponseLayout::apply(false,'','上传失败');
        }
    }

formData

js:

<script>
    $('#myForm').on('submit',function(e){
        e.preventDefault();//阻止默认的提交事件
        var formData = new FormData(this);//获取form表单的值
        var request = new XMLHttpRequest();
        request.open("POST", '/weChat/upload');
        request.send(formData);//发送到后端

    });
</script>

后端:

//上传文件
    public function upLoad(Request $request){
        $file = $request->file('document');
        if (!$file){
            return ResponseLayout::apply(false,'','请上传文件');
        }
        $path = $file->store('uploads','upload');
        $clientName = $file -> getClientOriginalName();
        $data['file_name'] = $clientName;
        $data['path'] = 'storage/'.$path;

        if (Notice::where('id',1)->update($data)){
            return ResponseLayout::apply(true,'','上传成功');
        }else{
            return ResponseLayout::apply(false,'','上传失败');
        }
    }

filesystems.php

'upload' => [
            'driver'      => 'local',
            'root'        => public_path('storage'),
            'visibility'  => 'public'
        ],

就这样,把文件重新命名,然后放到了public/storage/uploads下面

 类似资料: