To use the multiple file widget, you must add a data-attribute of multiple= "true"
. If you also want to include the "Remove" links as shown below, add a data-attribute of remove-links="true"
. You can optionallly set the maximum number of files allowed (defaults to 20) using data-max-files
.
When the uploader is configured for multiple file, the hidden input will be replaced with an "Add Files" button. The button text can be configured using the data-button-text
data-attribute.
<input class="simple-file-upload" data-multiple="true" data-remove-links="true" data-max-files="5" data-button-text="Add Files" type="hidden" name="user[avatar_url]" id="user_avatar_url" />
There are two methods to access the uploaded files - respond to the javascript event or read the form parameters on your server.
fileUploadSuccess
event is fired. The file list is available on the event
e.detail.files
. You can listen for the event like this:
//"el" is the element with class simple-file-upload
const el = document.getElementById("user_avatar_url")
el.addEventListener("fileUploadSuccess", (e) => {
console.log(e.detail.files)
})
//File object returned will be an array of file objects as show below (e.detail.files)
0:
cdnUrl: "file1_url"
name: "file1.jpg"
size: 1024
type: "image/jpeg"
1:
cdnUrl: "file2_url"
name: "file2.jpg"
size: 1024
type: "image/jpeg"
2:
cdnUrl: "file3_url"
name: "file3.jpg"
size: 1024
type: "image/jpeg"
[]
appended to the name. Most server side languages will parse this format into an array.
<input class="simple-file-upload" data-multiple="true" type="hidden" name="user[avatar_url]" id="user_avatar_url" />
<input class="simple-file-upload" data-multiple="true" type="hidden" name="user[avatar_url][]" id="user_avatar_url" value="file1_url" />
<input type="hidden" name="user[avatar_url][]" id="user_avatar_url2" value="file2_url" data-created-by-sfu ="true"/>
<input type="hidden" name="user[avatar_url][]" id="user_avatar_url3" value="file3_url" data-created-by-sfu ="true"/>
</form>
params.require(:user).permit(avatar_url: [])
params["user"]["avatar_url"]
The button fires a buttonCreated
javascript event when it is available to customize. The button id is available via e.detail.id
. Listen for the javascript event and replace the css with your own.
//"el" is the element with class simple-file-upload
const el = document.getElementById("id-of-hidden-input")
el.addEventListener("buttonCreated", (e) => {
const button = document.getElementById(e.detail.id)
button.classList.remove("btn-primary btn")
button.classList.add("your-class")
})