Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement