Home > Blockchain >  ERROR sending file.image Error: ENOENT: no such file or directory
ERROR sending file.image Error: ENOENT: no such file or directory

Time:07-17

Error: ENOENT when I test my route on POSTMAN. Hi so I have an issue with Error: ENOENT when I test my route on POSTMAN. So in this issue I have my image with undefined name at the begining.

If someone can help me it would be awesome thank you !

This is the picture of my sending on Postman:

Postman picture

and my folders backend:

Folders backend

My route with multer:

const express = require("express");
const router = express.Router();
const commentCtrl = require("../controllers/comment");
const { authJwt } = require("../middleware");
const { multerConfig } = require("../middleware");
const path = require('path')


const multer = require("multer");

var storage = multer.diskStorage({
  destination: './src/image/',
  filename: (req, file, cb) => {
    return cb(null, `${file.filename}_${Date.now()}${path.extname(file.originalname)}`);
  },
});

var uploadFile = multer({
   storage: storage,
   });
//creation d'une nouvelle sauce
router.post("/upload", [authJwt.verifyToken], uploadFile.single('image'), commentCtrl.createComment);
//afficher toutes les sauces
router.get("/",[authJwt.verifyToken], commentCtrl.getallComment);

module.exports = router;

My controller.js

const { Comment } = require("../models");
const fs = require("fs");
const path = require('path');

//créer post comment
module.exports.createComment  = async (req, res) => {
  if (!req.body.message) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
  }
  try {
    console.log(req.file);
   if (req.file == undefined) {
      return res.send(`You must select a file.`);
    }
    let { id, message, date, image} = req.body;
    image = fs.readFileSync(
      __dirname   "/images/"   req.file.filename
    )
    Comment.create({
      id, message, date, 
    }).then((image) => {
      console.log(image)
      fs.writeFileSync(
        __dirname   "/images/"   image.name,
        image.data
      );
      return res.send(`File has been uploaded.`);
    }).then((comment) => res.status(201).send(comment))
  } catch (error) {
    console.log(error);
    return res.send(`Error when trying upload images: ${error}`);
  }
};

CodePudding user response:

It solved I change :

 
image = fs.readFileSync( __dirname   "/images/"   req.file.filename ) 

by ----->

image = `${req.protocol}://${req.get("host")}/images/${req.file.filename}`,

And delete :

.then((image) => {
      console.log(image)
      fs.writeFileSync(
        __dirname   "/images/"   image.name,
        image.data
      );
      return res.send(`File has been uploaded.`);
    })

  • Related