DareRelaqz
DareRelaqz

Reputation: 123

Uploading an image file with Express.js, React, and MySQL

I need to make a page where a specific user (in this case an admin) can upload an image, save it on my mySQL database, and also in the 'uploads' folder in Express. In addition to that, I need a way to display the image later so that other users can see it when they log in. Are there any helpful packages on NPM that make this easier? Or is there a way to do this through vanilla React and Express?

Upvotes: 0

Views: 2056

Answers (1)

Rohit Dalal
Rohit Dalal

Reputation: 866

Try following package for Node - https://www.npmjs.com/package/multer

var multer = require('multer');
const storage = multer.diskStorage({

  destination: function (req, file, cb) {

    cb(null, appRoot+"/Uploads")

  },
  filename: function (req, file, cb) {

    cb(null, commonFunctions.generateAccessToken(90)+'.'+file.originalname.split('.')[1])

  }

})
global.upload = multer({storage: storage});

Then in your routes add upload middleware -

router.post("/addPersonalDetail", [upload.single("profile_pic") ], Controllers.serviceController.addPersonalDetail);

In your controller single filename is accessible via-

data.profile_pic_name = (request.file) ? request.file.filename : "";

Multiple Files are accessible via -

request.files[0].filename

Upvotes: 1

Related Questions