how to maintain an image after request error message in laravel?

1

How I have the problem that when sending a form with an image field when sending it and returning an error message of the request the image is lost ... How can I do to maintain the image?

    
asked by roman madrigal 30.03.2016 в 06:23
source

1 answer

1

The short answer is: you can not. You can not keep the selected image in the field once a form is submitted.

This happens for security reasons. Browsers should not send a document that the user has not explicitly selected (imagine they could and a malicious script will select files from the user's computer and send them without their consent).

And now the long answer: for the security reasons explained above does not keep the selected image ... but you can use some alternatives to not force the user to have to select a new image: well simulating that the image is still selected , or directly with the same image (if the form was not sent).

Here are some of them:

A. Use AJAX to send the data form

If instead of sending the form in traditional (with the submit, redirecting to the page specified in action ) you send it using AJAX, then you will never lose the image (because the page it does not change) and you will not have this problem.

If the form data does not validate, simply show the error message and you're done. The image will still be selected in the field.

B. Use the image you already have on the server

The image has already been sent to the server when the form was sent. If it is valid, save it somewhere temporarily and make it clear to the user that you already have it (eg: changing the field by a text message or even showing a link to the document / image).

When the form is resent, take the saved image and use it (now the form will not have an image unless you have given the user the opportunity to upload a new one, in that case, discard the temporary image and use the new one).

C. Use an "encoded" version of the image

You can not maintain the image or send an image that the user did not select ... but if the user selects a file, you can read it (eg with the FileReader API) and keep that data read. For example, if the user selects an image, you can read its content, encode it and save it in the LocalStorage to use it (eg as in the AJAX example, substituting the field for a thumb or directly for a hidden field) in case the form fails.

With this method, the image sent the second time is not exactly the same one that the user selected, but a copy of the original (either in base64 or the literal text, or as it was saved).

    
answered by 30.03.2016 в 07:22