Oleksandr Tatarinov
Oleksandr Tatarinov

Reputation: 323

not found file in node.js express

I try create my API server on node.js and get this err

{
    "error": {
        "message": "ENOENT: no such file or directory, open 'X:\\projects\\Brand-server\\uploads\\2018-06-08T07:45:55.176Zllg.png'"
    }
}

It happened after I tried save images for products in server but it not works.I use multer and Postman(for test API). Here is my code:

const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
const multer = require('multer')

const storage = multer.diskStorage({
    destination: function (req,file,cb) {
        cb(null,'./uploads/')
    },
    filename: function(req,file,cb){
        cb(null, new Date().toISOString() + file.originalname)
    }
})

const upload = multer({storage:storage})

const Product = require('../models/products')

router.post('/',upload.single('productImage'), (req, res, next) => {
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price
    })
    product.save()
        .then((result) => {
            console.log(result)
            res.status(201).json({
                createdProduct: result
            })
        })
        .catch(err => {
            console.log(err)
            res.status(500).json({
                error: err
            })
        })
})

Can you tell me how i can fix this err and why i get this? file structure enter image description here

Upvotes: 1

Views: 948

Answers (1)

Oleksandr Tatarinov
Oleksandr Tatarinov

Reputation: 323

I fix this!) Problem with storage.

const storage = multer.diskStorage({
    destination: function (req,file,cb) {
        cb(null,'./uploads/')
    },
    filename: function(req,file,cb){
        cb(null,Date.now() + '-' + file.originalname)
    }
})

Upvotes: 1

Related Questions