Working with files
Multimedia in the browser and server
Multimedia in the browser and server
Uploading files requires a few tweaks to our forms.
multipart/form-data encoding` handles the binary content of the file.
| |
Files will be ignored unless the form makes a
POSTrequest.
| |
Use an input element with type=“file” to open a file browser to locate a file.
| |
We can restrict which file types are allowed with the accept attribute.
| |
With these in place, the user can pick a file to attach to the request.
The formData will include a file object which can be extracted in the normal way.
A simple validation function.
| |
Schema for a simple file upload.
| |
Grab the validated file and pass it to a model.
| |
Handling the file is just the same as a string, except it is a File object.
Storing files in the database requires some simple manipulation of the file object.
We can store the name and type as text and add a BLOB field for the data.
Other tables can have associated files.
| |
| |
We deconstruct the File object. The bytes function gives us our BLOB data.
The image table has a random UUID for the URL.
| |
| |
You may want to have more specific tables with more fields.
Our model rebuilds the file.
Getting data back out of the database requires that we reconstruct the file object.
| |
The image table is standard
| |
The model acts as a simple file store.
Images are served as image files.
The response object is clever enough to add the correct headers.
| |
We can route requests to the controller to give each file a URL.
| |
Each individual image record has a unique route.
We can render images using
<img>elements.
| |
Setting the
srcattribute to the appropriate url.
If you have any questions, now is a good time to ask.
Thanks for listening