Custom File Storage

NOTE: This is only required if you want to host the files somewhere other than Amazon S3. Custom Amazon S3 is supported out of the box and requires no code changes.

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 centre 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 2 arrays, accepted and rejected.
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.accepted[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
    callback({ progress: 100, url: data.filelink })
  })
})