Laravel 5.1: keep uploaded file as old input

前端 未结 3 2118
庸人自扰
庸人自扰 2020-12-05 18:44

I\'m using a form in Laravel 5.1 to post some text and to upload a file. It looks like this (simplified version):

{!! Form::open(array(\'url\' => \'foo/ba         


        
3条回答
  •  半阙折子戏
    2020-12-05 18:57

    There seems to be a lot of questions around for the same issue (Form::file: How to repopulate with Input::old After Validation Errors and/or on Update?) and everyone with apparent knowledge says that is not possible.

    I would proppose a workaround that covers the following goals:

    • Keep form data and file input in case of failed Laravel validation
    • Use server side validation only. You don't need SHOULD NEVER USE javascript validation.

    The keyword of it all is AJAX. I would do the following:

    December 2017 update: Send all fields and attached files by a single AJAX POST

    1. Create an AJAX form (method GET POST) that contains everything except including file input. Remember that it requires to send the Laravel CSRF token.
    2. In the controller validation you need to make your responses (failed or success) to make a JSON output, so your AJAX send code can get the response in any case, and then you can show it in your browser

    This way you avoid to have files in any temporal state in your server.

    A more complex but improved version of this process, if you are worried about used bandwidth and you expect having errors in your input fields will be very common, you may do two (or more) AJAX POST validations: The first one with the input fields only, and if it's ok, send all fields (input fields again, now including the attached files) to attempt validation again and do actions with all data in case of success.

提交回复
热议问题