How to send form data together with file to mysql - mysql

Hello so i'm working on project which user can input data and upload file through form. I made this project with react js, node, express, and using mysql as database. Im currently having a problem to input name and upload file simultaneously. How to uplaod the data and file together with one button. sry for bad english
App.js
import React,{ useState, useEffect} from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [invoice, setInvoice] = useState("");
const [date, setDate] = useState ("");
const [currency, setCurrency] = useState ("IDR");
const [amount, setAmount] = useState("");
const [title, setTitle] = useState("");
const [path, setPath] = useState("");
const [attachment, setAttachment] = useState("");
const [dataList, setDataList] = useState([]);
useEffect(() => {
Axios.get('http://localhost:3001/api/get').then((response)=> {
setDataList(response.data);
})
})
const submitData = () => {
Axios.post('http://localhost:3001/api/insert', {
Invoice_No: invoice,
Invoice_Date: date,
Curr: currency,
Amount: amount,
Supplier: title,
Path: path
})
}
return (
<div className="App">
<p>CRUD Applicaiton</p>
<div className="formControl">
<label>Invoice No</label>
<input type="number" onChange={(e)=> {
setInvoice(e.target.value);
}} />
<label>Invoice Date</label>
<input type="date" onChange={(e)=> {
setDate(e.target.value);
}} />
<label>Currency</label>
<select onChange={(e)=> {
setCurrency(e.target.value);
}}>
<option value="IDR">IDR</option>
<option value="USD">USD</option>
<option value="YEN">YEN</option>
</select>
<label>Amount</label>
<input type="number" onChange={(e)=> {
setAmount(e.target.value);
}} />
<label>Title</label>
<input type="text" onChange={(e)=> {
setTitle(e.target.value);
}} />
<button onClick={submitData}>Add Data</button>
<button type='reset'>Reset</button>
</div>
<div>
<form method='POST' encType='multipart/form-data' action='http://localhost:3001/api/upload'>
<input type="file" name="DocumentFile" />
<button>ADD to DB</button>
</form>
</div>
</div>
);
}
export default App;
index.js
const express = require('express');
const fs = require('fs');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const mysql = require('mysql');
const exphbs = require('express-handlebars');
const multer = require("multer")
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "work"
});
const upload = multer({storage:multer.memoryStorage()});
app.use(cors());
app.use(express.json() || express.static(".public") || express.static(".upload"));
app.use(bodyParser.urlencoded({extended: true}));
app.get("/api/get", (req, res) => {
const sqlSelect= "SELECT * FROM invoice"
db.query(sqlSelect, (err, result)=>{
res.send(result);
});
})
app.post("/api/insert", (req, res) => {
const Invoice_No = req.body.Invoice_No
const Invoice_Date = req.body.Invoice_Date
const Currency = req.body.Curr
const Amount = req.body.Amount
const Title = req.body.Supplier
const sqlInsert = "INSERT INTO invoice(Invoice_No, Invoice_Date, Curr, Amount, Supplier) VALUES (?,?,?,?,?)"
db.query(sqlInsert, [Invoice_No, Invoice_Date, Currency, Amount, Title], (err, result)=>{
console.log(err)
});
})
app.post("/api/upload", upload.single('DocumentFile'), (req, res) => {
const Path = req.file.buffer.toString('base64')
q = "INSERT INTO invoice (Path) VALUES (?)"
db.query(q, [Path], (err, result) => {
console.log(Path)
})
})
app.listen(3001, ()=> {
console.log('running on port 3001')
});

Related

How to upload image/file to mysql but display it as file not as BLOB

Hello so i wanna try to upload data from form to mysql server using react as frontend and node.js as backend.
But i want to display/show the uploaded file as pdf not as BLOB. Is there a way to display the document/file as file in mysql so you can download the file easir or do you have to convert it in javascript? Thanks.
App.js
function App() {
const [employeeName, setName] = useState("");
const [employeeAge, setAge] = useState("");
const [employeePosition, setPosition] = useState("");
const [employeeSalary, setSalary] = useState("");
const [employeeFile, setFile] = useState();
const [dataList, setDataList] = useState([]);
const submitData = () => {
Axios.post('http://localhost:3001/api/insert', {
Name: employeeName,
Age: employeeAge,
Position: employeePosition,
Salary: employeeSalary,
Image: employeeFile
})
if(employeeName && employeeAge && employeePosition && employeeSalary && employeeFile != null){
alert("Berhasil ")
}else{
alert("Masukan Input")
}
}
return (
<div className="App">
<p>CRUD Applicaiton</p>
<div className="formControl">
<form>
<label>Name</label>
<input type="text" onChange={(e)=> {
setName(e.target.value);
}} />
<label>Age</label>
<input type="number" onChange={(e)=> {
setAge(e.target.value);
}} />
<label>Position</label>
<input type="text" onChange={(e)=> {
setPosition(e.target.value);
}} />
<label>Salary</label>
<input type="number" onChange={(e)=> {
setSalary(e.target.value);
}} />
<div className='fileUpload'>
<input type="file" onChange={(e)=> {setFile(e.target.value)}} />
</div>
<button onClick={submitData}>Add Data</button>
<button type='reset'>Reset</button>
</form>
</div>
</div>
);
}
export default App;
index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "coba"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post("/api/insert", (req, res) => {
const Name = req.body.Name
const Age = req.body.Age
const Position = req.body.Position
const Salary = req.body.Salary
const Image = req.body.Image
const sqlInsert = "INSERT INTO employee (Name, Age, Position, Salary, Image) VALUES (?,?,?,?,?)"
db.query(sqlInsert, [Name, Age, Position, Salary, Image], (err, result)=>{
console.log(result)
});
})
app.listen(3001, ()=> {
console.log('running on port 3001')
});

Display uploaded image link to mysql

this is my first project i made using react, node, and mysql. i have a form that contain data and upload file. I have succesfully uploaded file into node and stored it inside folder. The problem is i want to make a link to that uploaded file, so i can insert the link to mysql. This is so a person accessing the database can download the file. Is there a way to do that ?
index.js back end
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'Images')
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname))
}
})
const upload = multer({storage: storage});
app.post("/upload", upload.array('DocumentFile', 10), (req, res) => {
const Currency = req.body.Currency
const Title = req.body.Supplier
const Email = req.body.email
const InvoiceNo = req.body.InvoiceNo
const Invoice_Date = req.body.Invoice_Date
const Amount = req.body.Amount
const Description = req.body.Description
const Attachments = req.files[2]
q = "INSERT INTO payg(InvoiceNo, InvoiceDate, Title, Currency, Amount, Attachments) VALUES (?, ?, ?, ?, ?, ?)"
db.query(q, [InvoiceNo, Invoice_Date, Description, Currency, Amount, Attachments], (err, result) => {
console.log(Attachments)
res.send("Uploaded")
})
})
App.js
function App(props) {
const [invoice, setInvoice] = useState("");
const [date, setDate] = useState ("");
const [currency, setCurrency] = useState ("IDR");
const [amount, setAmount] = useState("");
const [title, setTitle] = useState("");
const [path, setPath] = useState("");
const [attachment, setAttachment] = useState("");
const [dataList, setDataList] = useState([]);
Axios.defaults.withCredentials = true;
return (
<div className="App">
<BasicExample />
<div className='formInput'>
<form method='POST' encType='multipart/form-data' action='http://localhost:3001/upload'>
<div className='textUser'>
<h1>{props.data}</h1>
</div>
<input className='inputForm' type="email" placeholder='Email - Disabled' name='email' disabled />
<input className='inputForm' type="number" placeholder='Invoice No' name='InvoiceNo' />
<input className='inputForm' type="date" placeholder='Date and Time' name='Invoice_Date' />
<input className='inputForm' type="text" placeholder='Description' name='Description' />
<select className='selectBox' name='Currency' onChange={(e)=> {
setCurrency(e.target.value);
}}>
<option value="IDR">IDR</option>
<option value="USD">USD</option>
<option value="YEN">YEN</option>
</select>
<input className='inputForm' type="number" placeholder='Amount' name='Amount'/>
<input className='custom-file-upload' type="file" name="DocumentFile" />
<button className='btnSubmit'>Submit</button>
</form>
</div>
</div>
);
}
If you have saved the image to a folder in your server node (eg ./your-folder/your-file-name.png). You can get that file name and save it to the database.
To access that file from express API:
app.get("/image", (req, res) => {
const filename = req.query.filename;
res.sendFile(filename, {
root: `./your-folder/`,
});
});
Get with url (at port 5000): http://localhost:5000/image?filename=your-file-name.png

error adding data to mysql column and all column counted as NULL

Hello so i started the project using react, node js, and mysql.
My goal is to create a form in frontend and want to add the data in form to mysql database.
But after submiting there is a error'INSERT INTO employee (Name, Age, Position, Salary) VALUES (NULL,NULL,NULL,NULL)'.
The problem here is in all column it says "cannot be null". How do i solve this.
App.js
import React,{ useState, useEffect} from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [employeeName, setName] = useState("")
const [employeeAge, setAge] = useState("")
const [employeePosition, setPosition] = useState("")
const [employeeSalary, setSalary] = useState("")
const submitData = () => {
Axios.post('http://localhost:3001/api/insert', {
Name: employeeName,
Age: employeeAge,
position: employeePosition,
Salary: employeeSalary
}).then(()=>{
alert('Berhasil')
})
}
return (
<div className="App">
<p>CRUD Applicaiton</p>
<div className="formControl">
<label>Name</label>
<input type="text" onChange={(e)=> {
setName(e.target.value);
}} />
<label>Age</label>
<input type="number" onChange={(e)=> {
setAge(e.target.value);
}} />
<label>Position</label>
<input type="text" onChange={(e)=> {
setPosition(e.target.value);
}} />
<label>Salary</label>
<input type="number" onChange={(e)=> {
setSalary(e.target.value);
}} />
<button type="submit" value="Submit" onClick={submitData}>Add Data</button>
<button type="reset" value="Reset">Reset</button>
</div>
</div>
);
}
export default App;
index.js (backend)
const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "coba"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post("/api/insert", (req, res) => {
const Name = req.body.employeeName
const Age = req.body.employeeAge
const Position = req.body.employeePosition
const Salary = req.body.employeeSalary
const sqlInsert = "INSERT INTO employee (Name, Age, Position, Salary) VALUES (?,?,?,?)"
db.query(sqlInsert, [Name, Age, Position, Salary], (err, result)=>{
console.log(err)
});
})
app.listen(3001, ()=> {
console.log('running on port 3001')
});
You need to change your backend code.
Try once with the following code:
app.post("/api/insert", (req, res) => {
const Name = req.body.Name
const Age = req.body.Age
const Position = req.body.position
const Salary = req.body.Salary
const sqlInsert = "INSERT INTO employee (Name, Age, Position, Salary) VALUES (?,?,?,?)"
db.query(sqlInsert, [Name, Age, Position, Salary], (err, result)=>{
console.log(err)
});
})

How to fix Converting circular structure to JSON error

I'm working on a project for my portfolio and decided I would do the registration page and backend first so that can be out of the way. I followed a tutorial with nodejs and mysql but I'm getting an error saying TypeError: Converting circular structure to JSON --> starting at object with constructor 'HTMLInputElement' | property '__reactFiber$g76m1cpwrsr' -> object with constructor 'FiberNode' --- property 'stateNode' closes the circle. I can't tell exactly where is error might be originating from or what is causing this issue. Any help would be appreciated
Registration page
import React, { useState } from "react";
import "../Styling/Register.css";
import axios from "axios";
function Register() {
const [userName, setUsername] = useState("");
const [userEmail, setUserEmail] = useState("");
const [userPassword, setUserPassword] = useState("");
const [userSubject, setUserSubject] = useState("");
const [account_type, setAcc_Type] = useState("");
const create_user = () => {
axios
.post("http://localhost:3001/register", {
userID: 1001,
userName: userName,
Email: userEmail,
password: userPassword,
subject: userSubject,
acc_type: account_type,
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
};
return (
<div className="form">
<input
type="text"
placeholder="FULL NAME"
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="text"
placeholder="Email"
onChange={(e) => setUserEmail(e.target.value)}
/>
<input
type="text"
placeholder="Password"
onChange={(e) => setUserPassword(e.target.value)}
/>
<input
type="text"
placeholder="Field/Subject"
onChange={(e) => setUserSubject(e.target.value)}
/>
<input
type="text"
placeholder="Tutor/Student"
onChange={(e) => setAcc_Type(e.target.value)}
/>
<button onClick={create_user}>Register</button>
</div>
);
}
export default Register;
My server side script in nodejs
const express = require('express');
const mysql = require('mysql');
const cors = require('cors');
const app = express();
app.use(express.json())
app.use(cors());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'tutor_locator'
});
app.post('/register', (req, res) => {
const userID = req.body.userID;
const userName = req.body.userName;
const Email = req.body.userEmail;
const password = req.body.userPassword;
const subject = req.body.userSubject;
const acc_type = req.body.account_type;
db.query(
'INSERT INTO users(User_ID, User_Name, User_Email, user_Password, User_Subject, Accout_Type) VALUES (?,?,?,?,?,?)',
[userID, userName, Email, password, subject, acc_type],
(err, result) => {
console.log(res);
}
)
})
app.listen(3001, () => {
console.log('server started');
});

400 Bad Request Cloudinary Upload Error in React + Nodejs + mySQl

I am currently building a Full stack Web App with React, MySQL, Nodejs, Express and Cloudinary, I am having issues uploading to Cloudinary, for security reasons, I didnt post my true upload_preset here
The code below is my React code:
import React, { useState } from 'react';
import "./Upload.css";
import Axios from 'axios';
function Upload() {
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [image, setImage] = useState([]);
const upload = () => {
const formData = new FormData();
formData.append("file", image[0]);
formData.append("upload_preset", "fzqyat");
Axios.post(`https://api.cloudinary.com/v1_1/williampepple/image/upload`, formData).then((response) => {
const fileName = response.data.public_id;
Axios.post("http://localhost:3001/upload", {
title: title,
description: description,
image: fileName});
});
;}
return (
<div className="Upload">
<h1>Create a Post</h1>
<div className="UploadForm">
<input type="text" placeholder="Title..."
onChange={(event) =>{setTitle(event.target.value);
}}
/>
<input type="text" placeholder="Description..."
onChange={(event) =>{setDescription(event.target.value);
}}
/>
<input type="file" onChange={(e) =>setImage(e.target.value)}/>
<button onClick={upload}>Upload</button>
</div>
</div>
)
}
export default Upload
Below is my Index.js file in my Nodejs Folder:
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors());
app.use(express.json())
const userRoute = require('./Routes/User');
app.use("/user", userRoute);
const uploadRoute = require('./Routes/Upload');
app.use("/upload", uploadRoute);
app.listen(3001, (req, res) => {
console.log("server running..");
});
Below is my Upload route file:
const express = require('express');
const router = express.Router();
const db = require('../config/db')
router.post('/', (req, res)=> {
const title = req.body.title
const description = req.body.description
const image = req.body.image
db.query(
"INSERT INTO Uploads(title, description, image) VALUES (? , ? , ?);", [title, description, image],
(err, results)=>{
console.log(err);
res.send(results);
}
);
});
module.exports = router;