Created
August 6, 2019 16:38
-
-
Save un-versed/f803fe17029ca0c86304cd89be7216b3 to your computer and use it in GitHub Desktop.
AdonisJs file upload 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
const { ServiceProvider } = require('@adonisjs/fold') | |
const path = require('path') | |
const fs = require('fs') | |
const Drive = use('Drive') | |
const Helpers = use('Helpers') | |
class FileUpload extends ServiceProvider { | |
register () { } | |
boot () { } | |
static async uploadToS3 (file, folder, oldPath) { | |
// If oldPath parameter is set then, delete the old picture | |
if (oldPath) { | |
const exists = await Drive.disk('s3').exists(oldPath) | |
if (exists) { | |
await Drive.disk('s3').delete(oldPath) | |
} | |
} | |
// Create a random name for file | |
const randomName = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15) | |
const fileName = `${randomName}_${Date.now()}.${file.subtype}` | |
// Sets the path and move the file | |
const filePath = `${path.resolve(`./tmp/${folder}/`)}/${fileName}` | |
await file.move(Helpers.tmpPath(folder), { name: fileName, overwrite: true }) | |
// Creates a readable stream from file and stores its size | |
const fileStream = await fs.createReadStream(filePath) | |
const fileSize = await file.stream.byteCount | |
// Uploads the file to Amazon S3 and stores the url | |
const s3Path = `${folder}/${fileName}` | |
await Drive.disk('s3').put(s3Path, fileStream, { ACL: 'public-read', ContentType: `${file.type}/${file.subtype}` }) | |
const fileUrl = await Drive.disk('s3').getUrl(s3Path) | |
// Destroy the readable stream and delete the file from tmp path | |
await fileStream._destroy() | |
await Drive.delete(filePath) | |
return { | |
name: fileName, | |
path: s3Path, | |
size: fileSize, | |
url: fileUrl | |
} | |
} | |
} | |
module.exports = FileUpload |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment