0

I'm creating a blog using ReactJS and MySQL.

I've already managed to create a table using MySQL workbench.

I have some states bound to some forms, to handle the data I want to insert in MySQL.

  const [file, setFile] = useState();
  const [fileName, setFileName] = useState("");
  const [date, setDate] = useState(null);
  const [title, setTitle] = useState("");
  const [text, setText] = useState("");

  const handleChangeImageUrl = (event) => {
    setFile(event.target.files[0]);
    setFileName(event.target.files[0].name);
  };

  const handleChangeDate = (event) => {
    setDate(event.target.value);
  };

  const handleChangeTitle = (event) => {
    setTitle(event.target.value);
  };

  const handleChangeText = (event) => {
    setText(event.target.value);
  };

And a button to send the data to the server using Axios

  const handleClickPublicar = async () => {
    try {
      const res = await Axios.post(
        `http://localhost:3001/publish/Noticias`,
        {
          file: file,
          fileName: fileName,
          date: date,
          title: title,
          text: text,
        }
      );
      console.log(res);
    } catch (err) {
      console.log(err);
    }
  };

On my server I have:

const express = require("express");
const app = express();
const mysql = require("mysql");
const cors = require("cors");

const db = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "password",
  database: "saude-vapor-postdata",
});

app.use(cors());
app.use(express.json());

app.post("/publish/Artigos", (req, res) => {
  const { file } = req.body;
  const { fileName } = req.body;
  const { date } = req.body;
  const { title } = req.body;
  const { text } = req.body;

  let SQL =
    "INSERT INTO postarticles (file, fileName,date, title, text) VALUES (?, ?, ?, ?, ?)";

  db.query(SQL, [file, fileName, date, title, text], (err, result) => {
    console.log(err);
  });
});

app.listen(3001, () => {
  console.log("Starting server...");
});

console.log(file) inside my react js application, I can access information about my image.

However console.log(file) inside the server is empty.

Does anyone know how to properly place an image inside a MySQL table.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
  • To handle file uploads you'll need something like [Multer](https://github.com/expressjs/multer#usage) in Express and [`Axios.postForm()`](https://github.com/axios/axios#files-posting) on the client side – Phil Jun 14 '22 at 23:24
  • ok... I knew the Multer... but I didnt know that I had to do this Axios.postForm() on client side.. thank you for you attention – Diego Bruno Jun 15 '22 at 01:24

0 Answers0