-1

This is my uploadRouter.js that I use to POST images to the server:

const express = require('express');
const bodyParser = require('body-parser');
const authenticate = require('../authenticate');
const multer = require('multer');
const cors = require('./cors');
const Images = require('../models/images');


const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/images');
    },

    filename: (req, file, cb) => {
        cb(null, file.originalname)
    }
});

const imageFileFilter = (req, file, cb) => {
    if(!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
        return cb(new Error('You can upload only image files!'), false);
    }
    cb(null, true);
};

const upload = multer({ storage: storage, fileFilter: imageFileFilter});

const uploadRouter = express.Router();
uploadRouter.use(bodyParser.json());

uploadRouter.route('/')

.post(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, upload.single('imageFile'),
 (req, res) => {
    Images.create(req.body)
    .then((image) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(req.file);
    }, (err) => next(err))
    .catch((err) => next(err));

})

And this is my models/image.js file:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var imageSchema = new Schema({
  fieldname: {
      type: String
  },
  originalname: {
      type: String
  },
  encoding: {
      type: String
  },
  mimetype: {
      type: String
  },
  destination: {
      type: String
  },
  filename: {
      type: String
  },
  path: {
      type: Boolean    
  },
  size:{
    type: Number
  }
}, {
  timestamps: true
});

var Images = mongoose.model('Image', imageSchema);
module.exports = Images ;

When I try to POST an image using the Postman, after posting successfully I get a result like this:

{
    "fieldname": "imageFile",
    "originalname": "home_header.jpg",
    "encoding": "7bit",
    "mimetype": "image/jpeg",
    "destination": "public/images",
    "filename": "home_header.jpg",
    "path": "public\\images\\home_header.jpg",
    "size": 58277
}

But when I send a GET request to the https://localhost:3443/images/ endpoint I get this result:

[

    {
        "_id": "5e8ef5fa98c70f30a8986070",
        "createdAt": "2020-04-09T10:16:26.796Z",
        "updatedAt": "2020-04-09T10:16:26.796Z",
        "__v": 0
    },
    {
        "_id": "5e8efb70070f0b39103cba71",
        "createdAt": "2020-04-09T10:39:44.196Z",
        "updatedAt": "2020-04-09T10:39:44.196Z",
        "__v": 0
    },
    {
        "_id": "5e90150dd9812057f81784f3",
        "createdAt": "2020-04-10T06:41:17.633Z",
        "updatedAt": "2020-04-10T06:41:17.633Z",
        "__v": 0
    }
]

Then I can't see the other fields like filename, originalname, etc that I need to know in my client side. So how can I store these extra fields alongside with the _id and createdAt, updatedAt, __v fields?

Hasani
  • 3,543
  • 14
  • 65
  • 125
  • 1
    Hi there! In your POST request handler, try calling `Image.create` with `req.file` instead of `req.body`, something like this `Images.create(req.file).then(...other existing codes...)` – Tunmee Apr 10 '20 at 10:29
  • 1
    Also, in your schema you have typo: `imageSchema.path : { type: Boolean }`, while it should be `String`. And where is your `GET` method? Are you running `Images.find().then((images) => {...})` ? – Valijon Apr 10 '20 at 10:52
  • @Tunmee: Thank you. Your help solved my problem but I have another problem here: https://stackoverflow.com/questions/61119340/core-js5873-error-typeerror-cannot-read-property-destination-of-undefined – Hasani Apr 10 '20 at 11:34
  • @Valijon: Thanks, I corrected it, but I still have a problem here: https://stackoverflow.com/questions/61119340/core-js5873-error-typeerror-cannot-read-property-destination-of-undefined – Hasani Apr 10 '20 at 11:34
  • Post please your `GET` route code – Valijon Apr 10 '20 at 11:41
  • @Valijon: Isn't it inside the codes of this link: https://stackoverflow.com/questions/61136030/how-to-store-more-information-on-the-server-when-post-a-file – Hasani Apr 10 '20 at 11:59
  • @Valijon: My Get request comes from `image.service.ts` file that I put there, and will be handled inside `imageRouter.js` file that I also put there. – Hasani Apr 10 '20 at 12:00
  • Hey @Valijon, I would submit the comment as an answer so that it can be obvious to others that this particular issue has been solved and also so that I can earn some SO rep :-) – Tunmee Apr 11 '20 at 17:14

1 Answers1

0

In your POST request handler, call Image.create with req.file instead of req.body, something like this:

uploadRouter.route('/')
  .post(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, upload.single('imageFile'),
    (req, res) => {
      Images.create(req.file)
        .then((image) => {
          res.statusCode = 200;
          res.setHeader('Content-Type', 'application/json');
          res.json(req.file);
        }, (err) => next(err))
        .catch((err) => next(err));
    });
Tunmee
  • 2,483
  • 1
  • 7
  • 13