Skip to content

Instantly share code, notes, and snippets.

@innocentEdosa
Forked from un-versed/FileUpload.js
Created September 16, 2022 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save innocentEdosa/065ea2617f8c3794d3185df2826f225e to your computer and use it in GitHub Desktop.
Save innocentEdosa/065ea2617f8c3794d3185df2826f225e 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment