2

I have created an server.js where I can upload any file to mongodb but I just want to modify in such a way that I can upload only image file uploading any other file gives error.Can anyone suggest me what can be done but using mongoose library is compulsory.I have edited the code with the suggestion provided.

server.js::

const express = require('express');
const bodyParser = require('body-parser');
const path= require('path');
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid= require('gridfs-stream');
const methodOverride = require('method-override');

const fileFilter = (req,file,cb) => {
    var filetypes = /jpeg|jpg/;
    var mimetype = filetypes.test(file.mimetype);
    var extname = 
filetypes.test(path.extname(file.originamname).toLowerCase());

    if (mimetype && extname) {
        return cb(null,true);
    }
    cb("Error:file upload only supports the following filetype-" 
+filetypes);
}

const app = express();
//Middleware

app.use(bodyParser.json());
app.use(methodOverride('_method'));
app.set('view engine', 'ejs');
//MOngo URI
const mongoURI = 'mongodb://localhost:27017/server_files_db';

//create mongo connection
const conn = mongoose.createConnection(mongoURI);

//Init gfs
let gfs;

conn.once('open', () => {
    //initialize stream
    gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection('uploads');
})

//create storage engine
const storage = new GridFsStorage({
    url: mongoURI,
    file: (req, file) => {
      return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {
          if (err) {
            return reject(err);
          }
          const filename = buf.toString('hex') + 
    path.extname(file.originalname);
              const fileInfo = {
             filename: filename,
             bucketName: 'uploads'
           };
          resolve(fileInfo);
        });
      });
     }
   });
   const upload = multer({ storage: storage, fileFilter: fileFilter });
 //Route GET
 //@dest uploads file to DB
 app.get('/',(req,res)=>{
     res.render('index');
 });

//@route POST /upload
//@dest uploads file to DB
app.post('/upload', upload.single('file'), (req,res) => {
     // res.json({file: req.file});
     res.redirect('/');
 });
 const port = 5000;

app.listen(port, () => console.log(`server started on port ${port}`));
Ajax
  • 99
  • 5
  • 13
  • Does this answer your question? [Filter files on the basis of extension using Multer in Express JS](https://stackoverflow.com/questions/38652848/filter-files-on-the-basis-of-extension-using-multer-in-express-js) – Prakash Karena Jan 21 '20 at 14:06
  • try this out https://stackoverflow.com/a/38692588/11982418 – Prakash Karena Jan 21 '20 at 14:12

0 Answers0