k365869's avatar

Submitting data after image upload

My site has a feature that allows users to create posts (like Facebook). I have a form with a "Message" input field and a button that allows users to upload images.

Right now, how I have the code set up is that when the user submits the form, my code will submit the data first, and then upload the images.

The problem with this is that if the user cancels the image upload half way through, the database record will exist (because the data was submitted before the image upload), but there will be no images uploaded.

So my solution to this is to upload the images first and submit the data after. The problem with this is that I'm not sure how I can tie the images to the data in a database record.

Should I upload all of the images to /tmp and then move the files to a permanent directory, like /var/www/html/website/public/img/uploads/<upload_id> where upload_id is the id of the database record?

What should I do if the user uploads an image, but closes the tab half way. Then there will be an image in /tmp that will stay there forever unless the directory is cleaned up. How would I clean it up?

Is this the best way to do this or are there better ways?

I'm using Laravel 5.3 and Dropzone.js.

Thanks.

0 likes
2 replies
greenwood360's avatar

I am curious as to why you are not including the image upload as a part of the rest of the data query for the database.

If you're using dropzone.js out of the box - you can have it submit your other form items by having them update to hidden form elements in your dropzone form:

Dropzone will submit any hidden fields you have in your dropzone form. So this is an easy way to submit additional data. You can also use the params option.

zachleigh's avatar

I initially upload all images to a tmp folder in /storage and use the Laravel's storage class to do the bulk of the work. I offer users a preview of the image and if that image is chosen as the new profile pic, I move it to an /images directory in /storage and save the path in the database.

I then use this pacakage to run a cron job that cleans up the /tmp folder every ten minutes.

If you're using Laravel 5.3, this video is pretty helpful: https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/12

Please or to participate in this conversation.