Skip to content

Instantly share code, notes, and snippets.

@begueradj
Forked from un-versed/FileUpload.js
Created August 6, 2019 16:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save begueradj/32d0f26cc9528419404ed9e8b4e2a9ae to your computer and use it in GitHub Desktop.
Save begueradj/32d0f26cc9528419404ed9e8b4e2a9ae to your computer and use it in GitHub Desktop.
AdonisJs file upload to S3
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
@muzammilversiani
Copy link

Hey @begueradj I am getting cb is not a function error. Any idea why I am getting this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment