Search code examples
javascriptphpformsfile-uploadstatamic

How can I associate file uploads with a form submission that has not yet been created?


I'm building a traditional server-rendered HTML application (using Statamic on top of PHP) that lets users create ideas. They visit a Create Idea form, fill out some questions, and click submit. Once they do so, the form sends a POST request to the server, which then saves the data, generating an ID (and slug) for the idea.

I'd now like to let users upload files as part of their idea. The old-fashioned way to do this, of course, would just be to add file inputs to the form, and then have everything submitted at once (data and files). The server could create an ID and then associate the files with the ID.

However, this approach has some downsides, not least of all the delay of having to wait for the files to be uploaded as part of the form submission process. More modern implementations appear to upload files as soon as they have been added (e.g., via drag-and-drop). I've identified FilePond as a front-runner, for instance, or else I would probably use Dropzone.js.

However, if the browser sends the file(s) before the user has submitted the form, how can I best associate the files with the form data? I don't yet have an ID to use.

This must be a solved problem. But I couldn't find any best practice via Google, hence this question. Possible solutions that occur to me:

  1. Generate a GUID as part of the form. Submit this with any file uploads. Save it (as a hidden field) as part of the form data, if and when the form is ultimately submitted.
  2. Require the user to submit the form (save draft) before enabling file uploads. Obviously not a great user experience.
  3. As a variation on 2) above, automatically submit the form via Ajax at some point before the user starts to upload files.

I'm leaning towards solution 1 but wanted to see what I might not be thinking of. 2 is not great because of the confusing UX, and 3 seems less than ideal too, for example because I might end up saving draft ideas that the user never actually saves themselves (and abandons), and partly because the slug that gets generated might be based off a missing or incomplete title, since the user might not have completed the title field before uploading files.


Solution

  • Here is my suggestion:

    • Upload the file immediately (after validating..)
    • make an entry in "files" table of your database with 1st a path/filename (make it unique!) and 2nd unique, long enough token
    • send that back to your form (as return from uploading) and
    • submit it with the form in an hidden input.

    Then create a cronjob that removes all unused files once an hour or so.