Guest User

Untitled

a guest
Oct 21st, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. const AWS = require('aws-sdk');
  2. const Busboy = require('busboy');
  3.  
  4. const BUCKET_NAME = '';
  5. const IAM_USER_KEY = '';
  6. const IAM_USER_SECRET = '';
  7.  
  8. function uploadToS3(file) {
  9. let s3bucket = new AWS.S3({
  10. accessKeyId: IAM_USER_KEY,
  11. secretAccessKey: IAM_USER_SECRET,
  12. Bucket: BUCKET_NAME
  13. });
  14. s3bucket.createBucket(function () {
  15. var params = {
  16. Bucket: BUCKET_NAME,
  17. Key: file.name,
  18. Body: file.data
  19. };
  20. s3bucket.upload(params, function (err, data) {
  21. if (err) {
  22. console.log('error in callback');
  23. console.log(err);
  24. }
  25. console.log('success');
  26. console.log(data);
  27. });
  28. });
  29. }
  30.  
  31. module.exports = (app) => {
  32. // The following is an example of making file upload with additional body
  33. // parameters.
  34. // To make a call with PostMan
  35. // Don't put any headers (content-type)
  36. // Under body:
  37. // check form-data
  38. // Put the body with "element1": "test", "element2": image file
  39.  
  40. app.post('/api/upload', function (req, res, next) {
  41. // This grabs the additional parameters so in this case passing in
  42. // "element1" with a value.
  43. const element1 = req.body.element1;
  44.  
  45. var busboy = new Busboy({ headers: req.headers });
  46.  
  47. // The file upload has completed
  48. busboy.on('finish', function() {
  49. console.log('Upload finished');
  50.  
  51. // Your files are stored in req.files. In this case,
  52. // you only have one and it's req.files.element2:
  53. // This returns:
  54. // {
  55. // element2: {
  56. // data: ...contents of the file...,
  57. // name: 'Example.jpg',
  58. // encoding: '7bit',
  59. // mimetype: 'image/png',
  60. // truncated: false,
  61. // size: 959480
  62. // }
  63. // }
  64.  
  65. // Grabs your file object from the request.
  66. const file = req.files.element2;
  67. console.log(file);
  68.  
  69. // Begins the upload to the AWS S3
  70. uploadToS3(file);
  71. });
  72.  
  73. req.pipe(busboy);
  74. });
  75. }
Add Comment
Please, Sign In to add comment