The Regular Way
Usually, when getting files from users, you can use a basic input
element with the type
attribute set to "file"
.
<form>
<label for="fileupload">Select a file to upload</label>
<input type="file" id="fileupload">
<input type="submit" value="Submit">
</form>
This generally works when you have a backend waiting to process file uploads. In the best case, you upload to a dedicated object store and return a reference to the file, and in the worst case, you store the whole file on your server.
The Filestack picker can take files from both local and cloud sources and generate URLs for them. This eliminates the need for upload handling in our backend, and we can instead attach the returned Filestack URLs to our form.
How might this look?
Replace the file input
Let’s modify the original form to use a hidden
input instead. Assume this field will become the URL of the newly uploaded file.
<form>
<label for="fileupload">Select a file to upload</label>
<input type="hidden" id="fileupload">
<input type="submit" value="Submit">
</form>
We will also add a button to trigger the picker open.
<form>
<label for="fileupload">Select a file to upload</label>
<input type="hidden" id="fileupload">
<button id="picker" type="button">Pick file</button>
<input type="submit" value="Submit">
</form>
So far, so good. We just need to get the returned URL of the uploaded file and update our form field. To do this, we can do a little DOM manipulation in vanilla JS.
Here’s the full demo:
Now your regular HTML file input is no longer needed, and you can submit references to your Filestack assets instead. There are many picker options to customize what kinds of files are accepted, and some mirror the options to HTML file inputs (like the accept
attribute).
Hopefully, this guide shows that, with a little knowledge of web technologies, you can integrate Filestack uploads into any form that expects user files.
Bonus: Add a thumbnail preview
<form>
<label for="fileupload">Select a file to upload</label>
<input type="hidden" id="fileupload">
<button id="picker">Pick file</button>
<div id="thumbnail-container"></div>
<input type="submit" value="Submit">
</form>
// Same setup as before...but change this function
function updateForm (result) {
const fileData = result.filesUploaded[0];
fileInput.value = fileData.url;
// If file is resizable image, resize and embed it as a thumbnail preview
if (['jpeg', 'png'].indexOf(fileData.mimetype.split('/')[1]) !== -1) {
const container = document.getElementById('thumbnail-container');
const thumbnail = document.getElementById('thumbnail') || new Image();
thumbnail.id = 'thumbnail';
thumbnail.src = client.transform(fileData.handle, {
resize: {
width: 200
}
});
if (!container.contains(thumbnail)) {
container.appendChild(thumbnail);
}
}
};