heroku ENOENT: no such file or directory while uploading

Viewed 114

i have a problem if you can help, i've deployed my app on heroku and it's working properly on localhost when i upload product picture when launching on localhost everything is working and the picture is added to my public folder and the url is passed to my Product image url field, but when doing the same on heroku deployed app it shows: "ENOENT: no such file or directory, open 'public/obNHUnF85G2kHtApYvix5D-1200-80-1617359184714.png" thx in advance

Here is my app.js

const express = require('express')
const morgan = require('morgan')
const mongoose = require('mongoose')
const jwt = require('jsonwebtoken');
var cors = require('cors')

const errorHandler = require('./middleware/error')
const app = express()
var corsOptions = {
    origin: "*",
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions))
app.use(express.static('public'))
app.use(express.json())
app.use(morgan('tiny'))
require('dotenv/config')
const productRouter = require('./Routes/ProductRouter')
const categoryRouter = require('./Routes/CategoryRouter');
const authRoute = require('./Routes/auth');
const userRoute = require('./Routes/user');
const OrderRouter = require('./Routes/OrderRouter');
const imagesRouter = require('./Routes/addImagesRoute');
const { static } = require('express');
const apiUrl = process.env.API_URL

const port = process.env.PORT;

mongoose
    .connect(process.env.CONNECTION_STRING, {
        useUnifiedTopology: true,
        useNewUrlParser: true
    })
    .then(() => {
        console.log('connected successfully')
    })
    .catch(err => {
        console.log(err)
    })

app.use(`${apiUrl}/products`, productRouter)
app.use(`${apiUrl}/categories`, categoryRouter)
app.use(`${apiUrl}/auth`, authRoute)
app.use(`${apiUrl}/users`, userRoute)
app.use(`${apiUrl}/orders`, OrderRouter)
app.use(`${apiUrl}/images`, imagesRouter)

app.use(errorHandler);

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

My Uploading Router

const express = require('express')
const { uploadImage, uploadGalleryImages } = require('../controllers/uploadController')
const { authorize, protect } = require('../middleware/auth')
const uploadRouter = express.Router()
const multer = require('multer')
const path = require('path')
const FILE_TYPE_MAP = {
    'image/png': 'png',
    'image/jpeg': 'jpeg',
    'image/jpg': 'jpg'
}

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        const isValid = FILE_TYPE_MAP[file.mimetype]
        let uploadError = new Error('invalid image type')

        if (isValid) {
            uploadError = null
        }
        cb(uploadError, 'public/')
    },
    filename: function(req, file, cb) {
        const fileName = file.originalname.split(' ').join('-')
        const extension = FILE_TYPE_MAP[file.mimetype]
        cb(null, `${fileName.split('.', 1)}-${Date.now()}${path.extname(file.originalname)}`)
    }
})

const uploadOptions = multer({ storage: storage })

uploadRouter.use(protect)
uploadRouter.use(authorize('publisher', 'admin'))

uploadRouter.post(
    '/:productId/image',
    uploadOptions.single('image'),
    uploadImage
);

uploadRouter.put('/:productId/images', uploadOptions.array('images', 8), uploadGalleryImages);

module.exports = uploadRouter;

Adding url and hash function

    const file = req.file
    if (!file) return res.status(400).send('No image in the request')
    const fileName = file.filename
    const basePath = `${req.protocol}://${req.get('host')}/`

    try {

        const product = await Product.findByIdAndUpdate(
            req.params.productId, {
                imageUrl: `${basePath}${file.filename.split('.', 1)}${path.extname(
          file.originalname
        )}`
            }, { new: true }
        );
        await product.save();
        const url = product.imageUrl;

        const hash = await handler(url.toString());
        const hashString = JSON.parse(hash).blurHash;

        await Product.findByIdAndUpdate(req.params.productId, {
            imageHash: hashString
        }, { new: true })
        product.save()



        res.send(product)
    } catch (error) {
        return next(new ErrorResponse(`an error occured : ${error}`, 400))
    }



})```

when i upload on localhost [Local host request and result][1]


when i upload on heroku server [Heroku][2]


  [1]: https://i.stack.imgur.com/Fp8OK.png
  [2]: https://i.stack.imgur.com/oaFuC.png

0 Answers
Related