M
M
maxemga2021-04-26 19:08:57
Node.js
maxemga, 2021-04-26 19:08:57

How to use multer and React?

I need to upload a file to the server (from input) and send the path to the database
. To do this, I use the multer library and the function:

const multer = require('multer')
const moment = require('moment')


const storage = multer.diskStorage({
    destination(req, file, cb) {
        cb(null, './uploads')
    },
    filename(req, file, cb) {
        const date = moment().format('DDMMYYYY-HHmmss_SSS')
        cb(null, `${date}-${file.originalname}`)
    }
})

const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg') {
        cb(null, true)
    }
    else {
        cb(null, false)
    }
}

module.exports = multer({
    storage,
    fileFilter
})

To find a file and send a request:
<form action="http://localhost:80/api/server/addArticle" method="POST" enctype="multipart/form-data">

And on the server took the file like this:
router.post('/addArticle', upload.single('img'), async(req, res) => {


But this is without using React, and now I am writing on React and I have a request to the server using fetch, and before the file I needed was using the action request in the form and in the multer library using this token, and the desired file is searched, but how to be in my situation, how to tell multer that this file needs to be saved on the server?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question