0
const upload = require('../middleware/upload')
const user = require('../models/user')

class Routes {
    constructor(app) {
        this.configureCors(app)
        app.use(upload)
        app.use('/fileupload', (req, res) => {
            res.send("test")
        })
    }
    configureCors(app) {
        app.use((req, res, next) => {
            res.setHeader('Access-Control-Allow-Origin', '*');
            res.setHeader('Access-Control-Allow-Methods', 'POST, PUT, DELETE, GET');
            res.setHeader('Cache-Control', 'no-cache');
            next();
        });
    }    
}

module.exports = Routes

upload.js

const path = require('path')
const multer = require('multer')

const storage = multer.diskStorage({
    destination : function(req, file, cb) {
        cb(null, 'uploads/')
    },
    filename : function(req, file, cb) {
        let extn = path.extname(file.originalName)
        cb(null, Date.now() + extn)
    }
})

const Upload = multer({
    storage : storage,
    fileFilter : function(req, file, callback) {
        if(
            file.mimetype == 'image/png' ||
            file.mimetype == 'image/jpg'
          ) {
              callback(null, true)
          } else {
              console.log("Only support jpg and png images")
              callback(null, false)
          }
    },
    limit : {
        fileSize : 1024 * 1024 * 2
    }
})

module.exports = Upload

I don't know where is the mistake Error TypeError: app.use() requires a middleware function probably video.js expecting to return function is that the error ? Please take a look and guide me on this.

I want to make it separate file for upload setting this up to via middleware

Thanks

2
  • Please provide the stack trace of the error. Commented Aug 4, 2020 at 12:25
  • TypeError: app.use() requires a middleware function, while adding app.use(upload) Commented Aug 4, 2020 at 12:26

1 Answer 1

1

You need to use the selectors provided by multer as mentioned in the docs here.

To select one file to upload, change your code to :

    //...
    constructor(app) {
        this.configureCors(app)
        app.use(upload.single('file'))   // <= changed line of code
        app.use('/fileupload', (req, res) => {
            res.send("test")
        })
    }
    //...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.