1

I work on a blog and I need to upload an image on my server. How I can do that with Node.js?

My code:

import React, { useState, useContext, useEffect } from 'react'
import { useHttp } from '../hooks/http.hook'
import {useMessage} from '../hooks/message.hook'
import { AuthContext } from '../context/auth.context';

import CKEditor from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';

const CreatePost = () => {
    const auth = useContext(AuthContext)

    const {request} = useHttp()
    const [form, setForm] = useState({
        title: '',
        text: '',
        author: auth.nick
    })

    const message = useMessage()

    const changeHandler = e => {
        setForm({...form,
            [e.target.name]: e.target.value}
        )
    }

    const addPost = async () => {
        const data = await request('/api/posts', 'POST', {...form})
        console.log(data)
        message(data)
    }

    const handleEditorChange = (e) => {
        console.log('Content was updated:', e.target.getContent());
    }

    return (
        <div>
            <div className="row">
                <div className="input-field col s12">
                    <input
                        id="title"
                        type="text"
                        className="validate"
                        name="title"
                        value={form.title}
                        onChange={changeHandler}
                        required
                    />
                    <CKEditor
                        config={{
                            ckfinder: {
                                // Upload the images to the server using the CKFinder QuickUpload command.
                                uploadUrl: 'http://localhost:5000/uploader'
                            }
                        }}
                        editor={ ClassicEditor }
                        data="<p>Hello from CKEditor 5!</p>"
                        onInit={ editor => {
                            // You can store the "editor" and use when it is needed.
                            console.log( 'Editor is ready to use!', editor );
                        } }
                        onChange={ ( event, editor ) => {
                            const data = editor.getData();
                            console.log( { event, editor, data } );
                        } }
                        onBlur={ ( event, editor ) => {
                            console.log( 'Blur.', editor );
                        } }
                        onFocus={ ( event, editor ) => {
                            console.log( 'Focus.', editor );
                        } }
                    />
                    <label htmlFor="title">Title</label>
                </div>
            </div>

            <a className="waves-effect waves-light btn" onClick={addPost}>Створити пост</a>
        </div>
    )
}

export default CreatePost

And index.js server on port 5000:

const express = require('express')
const mongoose = require('mongoose')

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

const app = express()

app.use(express.json({ extended: true }))

app.use('/api', require('./routes/posts.routes'))
app.use('/api/auth', require('./routes/auth.routes'))

const PORT = process.env.PORT || 5000

app.post('/uploader', multipartMiddleware, function(req, res) {
    var fs = require('fs');

    fs.readFile(req.files.upload.path, function (err, data) {
        var newPath = __dirname + '/../public/uploads/' + req.files.upload.name;
        fs.writeFile(newPath, data, function (err) {
            if (err) console.log({err: err});
            else {
                html = "";
                html += "<script type='text/javascript'>";
                html += "    var funcNum = " + req.query.CKEditorFuncNum + ";";
                html += "    var url     = \"/uploads/" + req.files.upload.name + "\";";
                html += "    var message = \"Uploaded file successfully\";";
                html += "";
                html += "    window.parent.CKEDITOR.tools.callFunction(funcNum, url, message);";
                html += "</script>";

                res.send(html);
            }
        });
    });
});

(There is more code, but that is the connection to MongoDB and starting the server.)

But it doesn't upload an image on the server. I get "Cannot upload file"

So, how can I upload an image with React ckfinder and server on Node.js?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
meln1337
  • 39
  • 1
  • 4
  • Have you inspected if the call to backend is being made on putting image in editor? Please open up Network Tab of Developer Tools in browser to watch if the API call is being made. This should be first debugging step. – MiKr13 Jan 28 '20 at 10:55

2 Answers2

0

As far as I understand the documentation, your response should be a json:

{ url: 'http://www.whereisyourimage.com/image.png' }

So the editor can replace the locally selected file with the uploaded version.

emiel187
  • 191
  • 2
  • 3
  • 9
-2

app.post('/images', multipartyMiddleware, (req, res)=>{ console.log(req.files);

//console.log("Path HERE TO FILE ::::::::::-",req.files.upload.path)

});

Nsamba Isaac
  • 357
  • 4
  • 14