Search code examples
uploadcare

How can I get the custom storage filename for uploaded images using UploadCare?


I want to use my own S3 storage and display the image that was just uploaded. How can I get the filename that was uploaded to S3? For example I can upload a jpg image to UploadCare. This is the output I can get: fileInfo.cdnUrl: "https://ucarecdn.com/6314bead-0404-4279-9462-fecc927935c9/" fileInfo.name: "0 (3).jpg"

But if I check my S3 bucket this is the file name that was actually uploaded to S3: https://localdevauctionsite-us.s3.us-west-2.amazonaws.com/6314bead-0404-4279-9462-fecc927935c9/03.jpg

Here is the javascript I have so far:

var widget = uploadcare.Widget('[role=uploadcare-uploader]');
widget.onChange(group => {
  group.files().forEach(file => {
    file.done(fileInfo => {
      // Try to list the file from aws s3
      console.log('CDN url:', fileInfo.cdnUrl);
      //https://uploadcare.com/docs/file_uploader_api/files_uploads/
      console.log('File name: ', fileInfo.name);
    });
  });
});


Solution

  • Filenames are sanitized before copying to S3, so the output file name can contain the following characters only:

    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_

    The following function can be used to get a sanitized file name:

    function sanitize(filename) {
      var extension = '.' + filename.split('.').pop();
      var name = filename.substring(0, filename.length - extension.length);
      return name.replace(/[^A-Za-z0-9_]+/g, '') + extension;
    }
    

    The final S3 URL can be composed of the S3 base URL, a file UUID, which you can obtain from the fileInfo object, and a sanitized name of the uploaded file.