0

Estoy creando una app, en la cual utilizo Cloudinary para almacenar imágenes y para enviarlas empleo React Js (axios para las peticiones) y Node Js, sin embargo la primera vez que realizo las petición post una para almacenar la imagen localmente, es decir en un fichero del proyecto, y posteriormente otra ruta para enviar la imagen almacenada localmente a Coudinary y su información a MongoDB, obtengo el siguiente error:

{ error: [Error: ENOENT: no such file or directory, open 'C:\Users\joshu_lmv4h9a\Documents\React_Proyects\cloudinary_gallery_app\backend\files\Intel i9.jpg'] { errno: -4058, code: 'ENOENT', syscall: 'open', path: 'C:\Users\joshu_lmv4h9a\Documents\React_Proyects\cloudinary_gallery_app\backend\files\Intel i9.jpg' } } (node:1188) UnhandledPromiseRejectionWarning: ReferenceError: image_route is not defined at C:\Users\joshu_lmv4h9a\Documents\React_Proyects\cloudinary_gallery_app\backend\src\routes\images.router.js:80:23 at processTicksAndRejections (internal/process/task_queues.js:93:5) (Use node --trace-warnings ... to show where the warning was created) (node:1188) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:1188) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Lo explico a grandes rasgos, cuando realizo las peticiones me arroja el error, en el cual básicamente me indica que el archivo, es decir, la imagen, no se encuentra en el directorio local, sin embargo cuando reviso el directorio, la imagen sí se guardó, posteriormente vuelvo a enviar las peticiones y funciona, me gustaría como solucionar dicho error; a continuación dejo mi código:

Rutas: - Con la primera ruta almaceno la imagen localmente y con la segunda ruta, envío dicha imagen a Cloudinary, guardo la información a en MongoDB y finalmente elimino la imagen almacenada de forma local.

router.post('/upload_image', (req, res, next) => {
    try {
        // Save de image in a local directory
        const newPath = './files/';
        const file = req.files.file;
        const filename = file.name;

        file.mv(`${newPath}${filename}`)
    } catch (ex) {
        console.log(ex)
    }
})

router.post('/', async (req, res, next) => {
    const f = new Date();
    const format_date = (d) => {
        return d.getDate() + '/' + (d.getMonth()+1) + '/' +d.getFullYear()
    }
    console.log(format_date(f))
    // Obtain data of the body
    const {image_name, description, image_original_name} = req.body;

    if (!image_name || !description) {
        next(createError(400, 'Error saving image. Missing data'))
    } else if (image_name && description) {
        try {
            // Create a directory
            const newPath = './files/';
            const image_route = `${newPath}${image_original_name}` 
            console.log(image_route)
            // Save de image in cloudinary
            const result = await cloudinary.uploader.upload(image_route)
            const image = new Image({image_name, description, url_image: result.url, public_id: result.public_id})
            await image.save()
            //Delete the image in the local directory 
            fs.unlink(image_route)
        } catch (ex) {
            next(createError(400, 'Error to save image. Missing data'))
            console.log(ex)
            fs.unlink(image_route)
        }

        res.json({
            message: 'The image has been saved successfully'
        });
    }
});

React Js:

Aquí tomo la infomación desde el formulario y realizo las peticiones mediante axios.

const Form = ({setOpenFrom, setEditingImage, editingImage}) => {
    // Contexts
    const {imageId, dataImageToEdit, setDataImageToEdit} = useImageToSearch();
    console.log(dataImageToEdit)

    const [image_name, set_image_name] = useState(dataImageToEdit.image_name);
    const [image_description, set_image_description] = useState(dataImageToEdit.description);
    const [form_data, set_form_data] = useState();
    const [image_original_name, set_image_original_name] = useState();

    const [image_url, set_image_url] = useState(dataImageToEdit.url_image);

    const send_image = (files) => {
        const formData = new FormData();
        formData.append('file', files)
        set_form_data(formData)
        set_image_original_name(files.name)
    }

    const handleSubmit = async (e) => {
        e.preventDefault();

        if (!editingImage) {
            if (image_name !== '' && image_description !== '') {
                // Almacena la imagen localmente
                axios.post('http://localhost:4000/upload_image', form_data)
                // Envía la información
                await axios.post('http://localhost:4000/', {
                    image_name: image_name,
                    description: image_description,
                    image_original_name: image_original_name
                })
    
                set_image_name();
                set_image_description();
                set_form_data();
                set_image_original_name();
                setOpenFrom(false);
            }
        } else if (editingImage) {
            if (image_name !== '' && image_description !== '') {
                axios.patch(`http://localhost:4000/${imageId}`, {
                    image_name: image_name,
                    description: image_description
                })

                setDataImageToEdit()
                setEditingImage(false)
                setOpenFrom(false)
            }
        }
    }

    const handleChange = (e) => {
        switch (e.target.name) {
            case 'image_name':
                set_image_name(e.target.value)
                break;
            case 'image_description': 
                set_image_description(e.target.value)
                break;
            default:
                break;
        }
    }

    return (
        <Container>
            <form onSubmit={handleSubmit}>
                <input 
                    type="text" 
                    name="image_name"
                    value={image_name}
                    onChange={handleChange}
                    placeholder="Image Name"
                    autoComplete="off"  
                    required  
                />
                <input 
                    type="text" 
                    name="image_description"
                    value={image_description}
                    onChange={handleChange}
                    placeholder="Image Description"
                    autoComplete="off"    
                    required  
                />
                {!editingImage &&
                    <>
                        <input 
                            type="file" 
                            id="image_file"
                            onChange={(e) => {
                                send_image(e.target.files[0])
                                set_image_url((window.URL || window.webkitURL).createObjectURL(e.target.files[0]))
                            }}
                        />
                        <label htmlFor="image_file">
                            <span>Select Image</span>
                        </label>
                    </>
                }
                <button>{!editingImage ? 'Save Image': 'Upgrade Image'}</button>
            </form>
            <div>
                <img src={image_url}/>
            </div>
        </Container>
    );
}

export default Form;

1 respuesta 1

0

Si a alguien se le presenta el siguiente error, la solución es la siguiente, pues, en el error nos indica que no se ha encontrado el archivo esperado en el directorio, hay 2 posibles problemas la estructura de directorios no coincide con lo que se espera (la ruta que indica el error) o el archivo no existe, entonces en el código la ruta está creada de la siguiente forma:

// Create a directory
const newPath = './files/';

Y orcurre el error, sin embargo, la manera correcta es la siguiente:

// Create a directory
const newPath =  process.cwd()+'/files/';

De tal forma el error estaría solucionado.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.