Custom File Storage
Who needs to do this?
This is only required if you want to host the files somewhere other than Amazon S3. Amazon S3 is supported out of the box and requires no code. You can simply add your AWS Keys and Bucket info under project settings.
By default, we have file storage support built-in with Amazon S3 that can be configured without any coding. If you need to store files somewhere other than Amazon S3 such as your local data center or your own cloud, it can be done by the following way.
Image Upload Callback
Register this callback function to handle image uploads.
unlayer.registerCallback('image', function(file, done) {
// Handle file upload here
})
The function returns 2 parameters. We'll call them file and done.
Parameter | Type | |
---|---|---|
file | Object | Contains an array, attachments . |
done | Function | This is the callback function to update progress bar and handling upload completion. |
Updating Progress Bar
You can call the done callback and pass an object with progress parameter containing the percentage of completion.
unlayer.registerCallback('image', function(file, done) {
// File upload code goes here
done({ progress: 10 }) // Updates the progress bar to 10%
})
Finishing Upload
Once the upload has finished, you have to pass the URL of the image to Unlayer.
unlayer.registerCallback('image', function(file, done) {
// File upload code goes here
done({ progress: 100, url: "URL OF THE FILE" })
})
Full Sample Code
We will use fetch to upload the file in this sample code. We'll post it to /uploads on our server. The following is a complete sample code that handles a file upload.
unlayer.registerCallback('image', function(file, done) {
var data = new FormData()
data.append('file', file.attachments[0])
fetch('/uploads', {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: data
}).then(response => {
// Make sure the response was valid
if (response.status >= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
}).then(response => {
return response.json()
}).then(data => {
// Pass the URL back to Unlayer to mark this upload as completed
done({ progress: 100, url: data.filelink })
})
})
Updated over 3 years ago