Я работаю над блогом, и мне нужно загрузить изображение на мой сервер. Как я могу сделать это с node js? Мой код:
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>
)
}
экспорт по умолчанию CreatePost
и индекс. js сервер на порту 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);
}
});
});
});
(есть больше кода, но это соединение с mongodb и стартовым сервером)
Но оно не загружает изображение на сервер. Я получаю «Невозможно загрузить файл». Итак, как загрузить изображение с помощью команды ckfinder и server на node js?