Skip to content
Advertisement

Return URL from file uploaded to AWS S3

I have a function that makes an API request containing the URL of a new file I just uploaded to AWS S3. And I have one function that only upload the file to S3.

I am having issues with returning this URL of the uploaded file.

Here is my code:

  myfunction(){
    let file; // assume the file is already set
    let filename; // assume the filename is already set

    let s3URL =  uploadFile(file, filename);
    console.log(s3URL); // this is returning a ManagedUpload object, I dont know how to get the URL from there
    makeAPIRequest(s3URL);
  }

  async uploadFile(file, fileName) {
    // S3 is from --> import * as S3 from 'aws-sdk/clients/s3';
    const s3 = new S3(
      {
        accessKeyId: 'myaccesskeyid',
        secretAccessKey: 'mysecretaccesskey',
        region: 'us-east-1'
      }
    );

    const params = {
      Bucket: 'my-bucket',
      Key: 'MyDirectory/' + fileName,
      Body: file
    };

    return await s3.upload(params, function(err, data) {
      console.log(err, data);
      return data; // URL is here inside data.Location
    });
  }

Here is the SDK doc with the upload example: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property

Thanks in advance 🙂

Advertisement

Answer

It seems that you want your uploadFile function to return the data from the s3.upload callback, rather than the result of the call itself. You can do that by returning your own Promise, and resolving it with the data you need:

  myfunction(){
    // ...

    // Remember to add `await` here
    const s3Data = await uploadFile(file, filename);
    const s3URL = s3Data.Location;
    
    // ...
  }

  async uploadFile(file, fileName) {
    // ...
    
    return new Promise((resolve, reject) => {
      s3.upload(params, function(err, data) {
        if (err) {
          reject(err);
        } else {
          resolve(data);
        }
      });
    });
  }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement