John Doe
John Doe

Reputation: 423

How can i use multer with react?

I am build a web app with Node.js and React and I am trying to store some files at my backend. For some reason i cant access to my req.path , although I configured all multer strategies.

const multer = require('multer')
const config = require('config')
const auth = require('../../middleware/auth')
const {check , validationResult } = require('express-validator');

const storage = multer.diskStorage({
    destination: function(req, file , cb){
        cb(null,'uploads/')
    },
    filename: function(req, file, cb){
        cb(null, req.user.id)
    }
});

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

my route:

router.post('/' , [auth,upload.single('image'),
    [
    check('status','Status is required').not().isEmpty(),
    check('skills','Skills is required').not().isEmpty(),
    check('gender','Gender is required').not().isEmpty()
    ]],
    async (req,res) => {// cant access to req.file.....}

and my react form:

 <div className="form-group">
                   <input type="text" placeholder="Choose profile image" name="profileImage" value={image}/>
                   <input type="file" placeholder="Upload"  enctype="multipart/form-data" name="image" onChange={(e) => onChange(e)}/>
                   <small className="form-text">The image must not be bigger then 5MB and only JPG\JPEG\PNG types</small>
 </div>

Please , what am i doing wrong?

Upvotes: 1

Views: 14324

Answers (2)

Mahad Ansar
Mahad Ansar

Reputation: 186

I have used multer in my backend application and this is how I have configured it and it works properly and stores required files in server file directory.

First, installing multer

 npm i multer --save

Second, initialize it at the top of required .js file

const multer = require("multer");

Now, configuring storage (storage location and filename)

  const storage = multer.diskStorage({
      destination: "./public/uploads/postimages/",
      filename: function (req, file, cb) {
        cb(
          null,
          file.fieldname + "-" + Date.now() + path.extname(file.originalname)
        );
      },
    });

Init multer function, (configure own file size)

Use array if you want to upload multiple files at once, 10 is the number of files, you can modify it as needed.

 const upload = multer({
      storage: storage,
      limits: { fileSize: 10000000000 },
    }).array("image", 10);

// Use .single("image"); if you want to upload a single file. // image is the name/key that is sent from frontend with the file(s).

If you are using array, you can create an api that stores file, which will look like this.

  try {
    let imagePath = "abc";
    let postId = req.params.postId;
    let imagesLinks = [];

    await upload(req, res, (err) => {
      if (err) {
        console.log(err);
      } else {
        if (req.files == undefined) {
          console.log("File not found.");
        } else {
          //image uploaded successfully

          req.files.map(function (file) {
            imagePath = "uploads/postimages/" + file.filename;
            imagesLinks.push(tmp);
          });
        }
      }
      res.status(201).send(imagesLinks);
    });
  }

For a single file, it looks as simple as this

 try {
    let imagePath = "abc";

    upload(req, res, (err) => {
      if (err) {
        res.status(300).send(err);
        console.log(err);
      } else {
        if (req.file == undefined) {
          res.status(301).send("image upload failed.");
        } else {
          //image uploaded successfully
          imagePath = "uploads/" + req.file.filename;
          storeImageLink(res, imagePath);
        }
      }
    });
  }

Upvotes: 4

ng-hobby
ng-hobby

Reputation: 2199

Look at these examples. They will be help you:

File Upload With Multer in Node.js and Express

Multer Storage:

// SET STORAGE
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})
 
var upload = multer({ storage: storage })

Handling File Uploads:

app.post('/uploadfile', upload.single('myFile'), (req, res, next) => {
  const file = req.file
  if (!file) {
    const error = new Error('Please upload a file')
    error.httpStatusCode = 400
    return next(error)
  }
    res.send(file)
  
})

Reactjs nodejs upload image — How to upload image using reactjs and nodejs (multer)

Node.js:

const path = require("path");
const multer = require("multer");

const storage = multer.diskStorage({
   destination: "./public/uploads/",
   filename: function(req, file, cb){
      cb(null,"IMAGE-" + Date.now() + path.extname(file.originalname));
   }
});

const upload = multer({
   storage: storage,
   limits:{fileSize: 1000000},
}).single("myImage");
const router = express.Router();
router.post("/upload", {
   upload(req, res, (err) => {
      console.log("Request ---", req.body);
      console.log("Request file ---", req.file);//Here you get file.
      /*Now do where ever you want to do*/
      if(!err)
         return res.send(200).end();
   });
};);

Upvotes: 0

Related Questions