SHARE
TWEET

Untitled

a guest Aug 18th, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { ServiceProvider } = require('@adonisjs/fold')
  2. const path = require('path')
  3. const fs = require('fs')
  4. const Drive = use('Drive')
  5. const Helpers = use('Helpers')
  6.  
  7. class FileUpload extends ServiceProvider {
  8.   register () { }
  9.  
  10.   boot () { }
  11.  
  12.   static async uploadToS3 (file, folder, oldPath) {
  13.     // If oldPath parameter is set then, delete the old picture
  14.     if (oldPath) {
  15.       const exists = await Drive.disk('s3').exists(oldPath)
  16.       if (exists) {
  17.         await Drive.disk('s3').delete(oldPath)
  18.       }
  19.     }
  20.  
  21.     // Create a random name for file
  22.     const randomName = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
  23.     const fileName = `${randomName}_${Date.now()}.${file.subtype}`
  24.  
  25.     // Sets the path and move the file
  26.     const filePath = `${path.resolve(`./tmp/${folder}/`)}/${fileName}`
  27.     await file.move(Helpers.tmpPath(folder), { name: fileName, overwrite: true })
  28.  
  29.     // Creates a readable stream from file and stores its size
  30.     const fileStream = await fs.createReadStream(filePath)
  31.     const fileSize = await file.stream.byteCount
  32.  
  33.     // Uploads the file to Amazon S3 and stores the url
  34.     const s3Path = `${folder}/${fileName}`
  35.     await Drive.disk('s3').put(s3Path, fileStream, { ACL: 'public-read', ContentType: `${file.type}/${file.subtype}` })
  36.     const fileUrl = await Drive.disk('s3').getUrl(s3Path)
  37.  
  38.     // Destroy the readable stream and delete the file from tmp path
  39.     await fileStream._destroy()
  40.     await Drive.delete(filePath)
  41.  
  42.     return {
  43.       name: fileName,
  44.       path: s3Path,
  45.       size: fileSize,
  46.       url: fileUrl
  47.     }
  48.   }
  49. }
  50.  
  51. module.exports = FileUpload
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top