Images is getting loaded from the local Folder But not from the uploads Folder which is declared static.
I have been trying to upload file from the browser, The image is uploaded sucessfully and saved successfully But while rendering the images from the uploads folder is not getting rendered
Sample Data from MongoDb Database
_id:1
...
image:"/images/mouse.jpg"
...
_id:2
...
image:"/uploads/image-1647229113730.jpeg"
...
Product Component
const Product = ({ product }) => {
return (
<Card className='my-3 p-3 rounded'>
<Link to={`/product/${product._id}`}>
<Card.Img src={product.image} variant='top' />
</Link>
<Card.Body>
...
</Card.Body>
</Card>
)
}
export default Product
The File herarchy is as follows
Repo
| backend
| server.js
| frontend
| public
| images
|mouse.jpg
| uploads
| image-1647229113730.jpeg
In server.js in the backend i have made the uploades folder static
const __dirname = path.resolve();
app.use("/uploads", express.static(path.join(__dirname, "/uploads")));
My problem is simple,
/images/mouse.jpg is accessible | /uploads/image-1647229113730.jpeg is not accessible
though both are there in the projects folder why?
I solved this by manually creating a variable named __dirname and assigned it the value of path.resolve() see example below
import path from 'path'; const __dirname = path.resolve(); app.use("/uploads", express.static(path.join(__dirname, "/uploads")));
and this solved the problem..
In your server.js you are declaring __dirname which overrides the implicitly declared __dirname that node provides for you.
So instead of using the value of path.resolve() which is the current working directory as described here you shouldn't declare __dirname yourself and use the __dirname that node provides. That is the path where your source file is located.
Then you can use path.join(__dirname,'../uploads') to get the path of your uploads folder. (The two dots are important)
EDIT:
I'm sorry. I've completely forgotten that __dirname isn't available in ES modules...
But here is another way that could work:
import { URL } from 'url';
const __dirname = new URL('.', import.meta.url).pathname;
app.use("/uploads", express.static(path.join(__dirname, "../uploads")));
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.