0

I've read all the answers but still can't wrap my head around what's wrong. I'm trying to display images from MongoDB at react, i can display the path but can't use it. Locallhost is running on port 8080.

The db object looks like this:

{"_id":{"$oid":"614cb6cb8b4b8b3bb8ac7342"},"fileName":"black-sandals-shoes.jpg","filePath":"addedItems\\2021-09-23T17-18-03.302Z-black-sandals-shoes.jpg","fileType":"image/jpeg","fileSize":"104.69-KB","type":"shoes","productType":"shoes","createdAt":{"$date":"2021-09-23T17:18:03.313Z"},"updatedAt":{"$date":"2021-09-23T17:18:03.313Z"},"__v":0}

At server.mjs (addedItems is the folder which stores the images at server side)

app.use('/api/addedItems', express.static(path.join(__dirname, 'addedItems'))); 

Item component:

export default function Item({ id, filePath, type, productType }) {
  return (
    <div className="item">
      {`http://localhost:8080/${filePath}`}
      <img
        src={`http://locallhost:8080${filePath}`}
        className="item-image"
        alt="item-img"
      />
      {/*<span>{type}</span>*/}
      <span>{productType}</span>
      <button>Delete from closet</button>
    </div>
  );
}

And that's what I get :

http://locallhost:8080/addedItems\2021-09-23T17-18-03.302Z-black-sandals-shoes.jpgitem-img
shoes
Delete from closet

Help me if you can :))

Kartikey
  • 4,516
  • 4
  • 15
  • 40

1 Answers1

0

I can see a typo here: <img src={`http://locallhost:8080${filePath}`} className="item-image" alt="item-img"/> change it to localhost with one 'l'. Additionally make sure on the server side that the folder where the images are saved is public. I found a similar topic here: Load local images in React.js

Edit to your comment: This is the exact code I found on multer documentation for diskStorage file uploading.

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix)
  }
})

const upload = multer({ storage: storage })

I strongly suggest you to take this and make any changes required. Also make sure the path is correct and that you have the upload variable at the bottom.

Nick Gr
  • 105
  • 10
  • Ok, thanks. but now that i've changed folders place to public, i have to change the path for "multer" , when i change the path - it stops uploading at all... const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, '../../react-app/public/addedItems'); }, filename: (req, file, cb) => { cb(null, new Date().toISOString().replace(/:/g, '-') + '-' + file.originalname); } }); Any thoughts? – Anna Fridman Sep 24 '21 at 17:22