简体   繁体   中英

How to accessing React public folder from the server folder

I want to upload an image to react public folder using multer NodeJs. It was fine in development but when I deployed it, it doesn't work. It looks like the multer couldn't upload/take reference to the public folder.

this is my folder structure :

/client
   /public
      /img
.
.
.
/routes
   /api
      /employee.js
server.js

Here is what I've done :

server.js

// Access public folder
app.use(express.static("client/public/img"))

employee.js

// Set storage engine
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, path.join(__dirname, "../../client/public/img/profilePicture"))
  },
  filename: (req, file, cb) => {
    cb(null, file.fieldname + path.extname(file.originalname))
  }
})

I saw the source from developer tools and it doesn't upload the file, yet it works on development.

Thank you for your help!

multer can take reference from public folder, but you need set the endpoint or path to upload to public folder. for example to make a folder public yo do: app.use('/endpoint/to/access/public/folder', express.static(path.resolve("client/public")))

also, your server.js is on your root folder as you client folder, so you can do something like that:

app.use('/public', express.static(path.join(__dirname,'client/public')));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM