Tuesday 15 August 2017

I can't upload an image to S3 in my Node API via multer.

I have a backend API, but I haven't deployed it yet, because I first need make sure the API can upload images to my S3 Bucket.I spent the last two days Googling non-stop on how to to do so, and I ended up writing this code in the process.My app is a website where people can create and share recipes. I want the user to be able to upload a profile pic for themselves, and have it so that the user has to upload a picture of their own meal whenever they create a recipe.Here is the code for a file called userRouter.js , where I try to upload a profile pic to Amazon S3. This isn't all the code in the file, only the relevant lines where I try to upload an image to S3.const bcrypt = require('bcryptjs'); const authentication = require('../controllers/authentication'); const express = require('express'); const passport = require('passport'); const passportService =require('../services/passport'); const config = require('../config/config'); const User = require('../model/user'); const router = express.Router(); const mongodb = require('mongodb'); const mongoose = require('mongoose'); const jwt = require('jsonwebtoken'); mongoose.Promise = Promise; const Recipe = require('../model/recipe'); ///!!!! NEW !!!!// const AWS = require('aws-sdk'); const fs = require('fs'); AWS.config.loadFromPath('./config/aws-config.json'); const bucket = new AWS.S3({params: {Bucket: 'deelish'}}); const multer = require('multer'); const upload = multer({ storage: multer.memoryStorage(), limits: {fileSize: 52428800} }); router.post('/uploadProfilePic', authentication.verifyOrdinaryUser, upload.single('avatar'), (req, res, next) => { bucket.putObject({ Bucket: 'deelish', //// req.decoded.id is the id of the user who logs into the app via the authentication.verifyOrdinaryUser function Key: String(req.decoded.id), Body: req.file.buffer, ACL: 'public-read' }, (err) => { if (err) return res.status(400).send(err); res.send('File uploaded to S3'); }); }); However, this route does not work whenever I try to test it in Postman. The error message I get is "SyntaxError: Unexpected token �" and I have no idea what any of that means.

Submitted August 15, 2017 at 09:44PM by T-Dot1992

No comments:

Post a Comment