Background
When you build a form in “Rails way”, you don’t have to do much on your own.
It automatically validates the parameter, and re-renders the form with proper messages in the event of errors.
However, when it comes to file upload form, things get complicated.
For instance, when the form is redisplayed because of the form error, the file input value is lost.
You don’t want to make users select the same file again, just because they mistyped their email address or phone number. Especially when they chose
a bunch of files to upload. It’s also bad in terms of website performance (We don’t want them to send large image files again and again).
We could use javascript file upload plugins (lots of them are opensource, cool, well animated and fantastic). But they normally make source code difficult to manage
if you’ve been doing things in “Rails way”.
Here I’ll introduce a way to build a file upload form in “Rails way”, which gets along with Rails activeform and requires minimum effort to build, but still does enough.
Concretely,
- Uploads multiple files at a time.
- Can add/remove multiple file input fields dynamically.
- Shows preview when an image file is chosen.
- If an errors exist in the form, the file inputs memorize and redisplay the selected file.
- Also, the server caches the once-uploaded-file in the event of form redisplay, so no additional network traffic occurs.
- Can remove existing files.
- Use plain html form, NOT xhr (therefore, no file drag and drop feature).
See Github Repository for the complete app.