Meteor.js REST API POST image data using Postman

629 views Asked by At

I am working on API creation for a mobile native app and need to create a REST API to upload a user profile pic. But when I am trying to upload the image in a POST request it's showing undefined.

This is my code in the app/server/server.js file:

if(Meteor.isServer) {
   Router.route('/api/uploadpic/', { where: 'server' })
   .post(function () {

     let response;
     console.log(this.request.body.file);

     this.response.setHeader('Content-Type', 'application/json');
      this.response.end(JSON.stringify(response));

  });
}

After spending a lot of hours I did not get anything useful. Do I need to use any package for this? Postman api request http://prntscr.com/ojfcvj

2

There are 2 answers

0
Jacki On

Not sure if it helps but try to change Content Type from application/json to 'multipart/form-data'

2
Zaw Hlaing Bwar On

1) You will have to create an express app and bind with Meteor WebApp
2) Use multer for photo uploads on nodejs and meteor

import { WebApp } from 'meteor/webapp';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import path from 'path';
const multer = require('multer');

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('*', cors());


// use multer({ dest: 'uploads/' }) if you have desire folder
// I used memory storage here
// 'avatar' is the post request field name for the file
const uploader = multer({ storage: multer.memoryStorage() }).single('avatar');
app.post('/uploads', uploader, Meteor.bindEnvironment(async(req, res, done) => {
   try {
        //you can get the file in req.file

        let fileName = req.file.originalname.replace(/\s/g, '_');
        let imageEncrypt = req.file.buffer.toString('base64');

        // Do whatever you want
   } catch (err) {
     res.status(404).end(err.message);
   }
}));

WebApp.connectHandlers.use(Meteor.bindEnvironment(app));