Created
June 22, 2022 06:20
-
-
Save mubasshir/61badedbdb974e224677147b43c7b04f to your computer and use it in GitHub Desktop.
Upload image from Axios to S3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class uploadToS3 { | |
async downloadRemoteFile(url: string): Promise<any> { | |
return new Promise((resolve, reject) => { | |
// make request | |
// import axios | |
axios({ | |
url: url, | |
method: 'GET', | |
responseType: 'arraybuffer', | |
decompress: false, | |
}).then(async response => { | |
const date = new Date(); | |
// unique file name | |
const fileName = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}-${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}-${date.getMilliseconds()}.jpg`; | |
// add sub folder path | |
const subFolderPath = 'api/import/images/'; | |
const s3Response = await this.uploadToS3(response.data, subFolderPath + fileName) | |
resolve(s3Response); | |
}); | |
}); | |
} | |
uploadToS3(data: any, fileName: string): Promise<any> { | |
return new Promise((resolve, reject) => { | |
if (!data) { | |
reject("No data"); | |
} | |
try { | |
// upload to s3 | |
// import S3 from @aws-sdk/client-s3 | |
const s3 = new S3({ | |
region: 'ap-south-1', | |
credentials: { | |
accessKeyId: "KEY_GOES_HERE", | |
secretAccessKey: "SECRET_GOES_HERE", | |
}, | |
}); | |
const params = { | |
Bucket: 'BUCKET_NAME_GOES_HERE', | |
Key: fileName, | |
Body: data, | |
ACL: 'public-read' | |
}; | |
// save file | |
s3.putObject(params, (err, data) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(data); | |
} | |
}); | |
} catch (error) { | |
console.error(error); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment