Как хранить больше информации на сервере, когда POST файл? - PullRequest
0 голосов
/ 10 апреля 2020

Это мой uploadRouter.js, который я использую для отправки изображений на сервер:

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));

})

И это мой models/image.js файл:

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 ;

Когда я пытаюсь POST изображение с помощью почтальона, после успешной публикации я получаю такой результат:

{
    "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
}

Но когда я отправляю запрос GET на конечную точку https://localhost: 3443 / images / Я получаю такой результат:

[

    {
        "_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
    }
]

Тогда я не вижу других полей, таких как filename, originalname и т. Д. c, которые мне нужно знать на стороне клиента. Итак, как я могу сохранить эти дополнительные поля вместе с полями _id и createdAt, updatedAt, __v?

1 Ответ

0 голосов
/ 11 апреля 2020

В вашем обработчике POST-запроса вызовите Image.create с req.file вместо req.body, что-то вроде этого:

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));
    });
...