Guest User

Untitled

a guest
Mar 23rd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. /**
  2. * Dependencies
  3. */
  4.  
  5. const express = require('express')
  6. const Multer = require('multer')
  7. const Busboy = require('busboy')
  8. const os = require('os')
  9. const fs = require('fs')
  10. const path = require('path')
  11.  
  12. const app = express()
  13.  
  14. app.get('/', (req, res, next) => res.json({ cool: true }))
  15.  
  16. app.post('/upload', (req, res, next) => {
  17. console.log('upload?')
  18. console.log(req.rawBody)
  19. const busboy = new Busboy({ headers: req.headers })
  20. // This object will accumulate all the uploaded files, keyed by their name.
  21. const uploads = {}
  22. const tmpdir = os.tmpdir()
  23.  
  24. // This callback will be invoked for each file uploaded.
  25. busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
  26. console.log(`got file ${filename}`)
  27. // Note that os.tmpdir() is an in-memory file system, so should
  28. // only be used for files small enough to fit in memory.
  29. const filepath = path.join(tmpdir, filename)
  30. console.log(filepath)
  31. uploads[fieldname] = filepath
  32. file.pipe(fs.createWriteStream(filepath))
  33. })
  34.  
  35. // This callback will be invoked after all uploaded files are saved.
  36. busboy.on('finish', () => {
  37. // *** Process uploaded files here ***
  38.  
  39. for (const name in uploads) {
  40. const file = uploads[name]
  41. fs.unlinkSync(file)
  42. }
  43. return res.json({ message: `file uploaded` })
  44. res.end()
  45. })
  46.  
  47. busboy.end(req.rawBody)
  48. })
  49.  
  50. module.exports = { app }
Add Comment
Please, Sign In to add comment