ftiersch's avatar

"Caching" a fileupload before form validation

Hi guys (and gals),

on my current project I stumbled across the following problem:

I'm building an application that allows visitors to participate in a raffle. There are different types of raffles - one of them is a file upload (so user uploads his favorite vacation picture and has the chance to win something for example). I'm validating the form (there is just one form for all raffle types which changes depending on type) via a FormRequest which works awesome except for one problem:

If the user uploads a file and makes another mistake (forgetting a required field / wrong captcha etc) I'd like to "cache" the file already so he doesn't have to upload the file on every try. Problem is I don't even get to my controller since the FormRequest already bounces the request back with errors.

Now I'm thinking about doing the caching part in a middleware. Is that the approach to go or is there maybe a better way to save an uploaded file somewhere before FormRequests are validated?

Thanks for any input!

0 likes
3 replies
krzemo's avatar

How are you validating the form? Are you using some kind of ajax upload? Does the file get uploaded to the server before form gets validated? From top of my head:

  1. Upload the file
  2. Store its details (id) in users's session together with raffle info (id?)
  3. Pre-populate the form (hidden field) or just send the info back to the form ...
bobbybouwmann's avatar

You can't keep files in the request for security reasons. The only option would be using javascript validation, so don't let the user submit the form before everything is correct.

ftiersch's avatar

I'm validating by FormRequest so right now there is no Ajax upload (though that would be my fallback solution).

What I'm trying to do:

  1. User selects a file, forgets captcha, clicks "Participate" -> POST Request is sent with the file
  2. A middleware is executed (before FormRequests) which takes the uploaded file and moves it to a temporary folder, saves it in the user session
  3. FormRequest is invalid, user gets sent back to form, his uploaded image is shown "to show him that he already chose that file"
  4. He inputs the captcha, clicks "Participate" again, POST Request is sent again (this time without the file because he already uploaded it)
  5. FormRequest goes through, Participant is created and the temporary uploaded file is associated with it

Please or to participate in this conversation.