Display uploaded image link to mysql - 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

Related

Not able post data from useState to Mysql

I am trying to post the input data from useState to Mysql but its just not happening. While I am able to get the data from the database to the page but when it comes to posting I don't know how to send data from state hooks to mysql when there are many values. Please take a look
Code from where i am sending the form data
import React,{useState , useRef} from "react";
import "./AddProjects.css"
import axios from "axios";
import Projects from "../Projects/Projects";
import {BiChevronLeftCircle,BiChevronRightCircle} from "react-icons/bi"
export default function AddProjects() {
const [AddProjects,setAddProjects] = useState({
ProjectName:"",
Discription:"",
git:"",
Img:""
})
const [getQuery,setGetQuery] = useState({
projectList:[]
})
const inputFile = useRef(null)
function handleChange(e) {
const {name , value} = e.target;
setAddProjects(newProjects => ({
...newProjects,[name]:value
}))
}
function imgChange(e) {
setAddProjects({ ...AddProjects, Img: URL.createObjectURL(e.target.files[0]) });
}
function getProjectList() {
axios.get(`http://localhost:3060/projects`)
.then((response) => response.data)
.then(response2 => {
setGetQuery({projectList : response2})
})
}
function onSubmitHandler(e) {
axios.post(`http://localhost:3060/addProjects`,{
ProjectName: AddProjects.ProjectName,
Discription:AddProjects.Discription,
git:AddProjects.git,
Img:AddProjects.Img
})
getProjectList()
}
return(
<>
<div className="AddProjects">
<form onSubmit={onSubmitHandler} method="POST" encType="multipart/form-data" >
<h2>Add New Project</h2>
<input type="text" placeholder="Project Name..." name="ProjectName" onChange={handleChange}/>
<input type="text" placeholder="Project Discription..." name="Discription" onChange={handleChange}/>
<input type="text" placeholder="Git Repository/Code..." name="git" onChange={handleChange}/>
<input type="file" accept="image/jpg,image/jpeg" name="Img" onChange={imgChange} ref={inputFile} />
<button type="button"onClick={() => inputFile.current.click()}>Add New Image</button>
<button type="submit" >Submit Project</button>
</form>
<button onClick={getProjectList}>click me </button>
</div>
<div>
<div className="Section-Projects" >
<h1>My Projects </h1>
{/* <Link to={checkBox?'/AddProjects':""} ><button className="Add-newProject" onClick={onStateChange}><IoIosAddCircleOutline/></button></Link> */}
<div className="Projects">
<button className="arrowLeft"><BiChevronLeftCircle /></button>
<div className="Single">
{getQuery.projectList.map((gettingQuery) =>
<Projects
ProjectId={gettingQuery.ProjectId}
ProjectName={gettingQuery.ProjectName}
Discription={gettingQuery.Discription}
git={gettingQuery.git}
Img={gettingQuery.Img}
/>
)}
</div>
<button className="arrowRight"><BiChevronRightCircle /></button>
</div>
</div>
</div>
</>
)
};
As you can see i want to send 4 things to the mysql table but i don't think the this is the way to do it and i just can't figure it out
Code for my file that is sending data
const express = require('express');
const cors = require('cors')
const PORT = 3060;
const db = require('./Database')
const bodyParser = require('body-parser');
const { response } = require('express');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/projects', (req,res) => {
const TASK_QUERY = `SELECT * FROM addprojects.newproject`;
db.query(TASK_QUERY , (err, response) => {
if(err) res.status(404).send('somthings wrong')
else res.send(response)
})
});
app.post('/addProjects', (req,res) => {
const ADD_QUERY = `INSERT INTO addprojects.newproject VALUES('${req.body.data}')`;
db.query(ADD_QUERY, (err) => {
if (err) console.log(err)
else res.send('Query added sucsessfully')
})
} );
app.listen(PORT, () => {
console.log('app is listning to port 3000')
})
I think while the post method is correct the Value is not so please help I am on this for 2 days Any suggestion will be help full
INSERT INTO tablename (columnName1, columnName2) VALUES ('Company Inc', 'Highway 37')
For backend:
You don't mention the columns name, it doesn't know which field belongs to which column in the table.
For Frontend:
axios.post(`http://localhost:3060/addProjects`,{
ProjectName: AddProjects.ProjectName,
Discription:AddProjects.Discription,
git:AddProjects.git,
Img:AddProjects.Img
})
ProjectName,Discription,git,Img make these keys name exact to your column names.
And you are uploading an image in this api so convert your data from front in formdata then pass that data in api and on backend you will that data in formdata

How to send form data together with file to 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')
});

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')
});

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)
});
})

React prevent Duplicate record input?

How i can prevent duplicate record input especially email and student number And show the message if the registration is accepted or it has duplicate record?
It accept data and when a set the email and the student number unique in the MySQL db it will not accept data but their is no message. It only show message in the terminal of visual studio that the email and student number is unique
Front end
import React from 'react'
import { useState } from 'react';
import Axios from 'axios';
import { useNavigate} from 'react-router-dom'
function Register() {
let navigate= useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [student_num , setStudnum] = useState(0);
const [RegisterStatus, setRegisterStatus] = useState("");
const [studentList, setStudentList] = useState([])
const addStudent = ( ) =>{
Axios.post("http://localhost:3001/create", {
email: email,
password: password,
student_num : student_num ,
}).then(()=>{
console.log("sucess")
});
};
return (
<form>
<div className="information">
<div className="App">
<label>Email:</label>
<input type="text" onChange={(event) => {
setEmail(event.target.value);
}} required />
<label>Password:</label>
<input type="password" onChange={(event) => {
setPassword(event.target.value);
}} required/>
<label>Student Number:</label>
<input type="number" onChange={(event) => {
setStudnum(event.target.value);
}}required/>
This is the MySQL connection / backend
app.post("/create", (req, res) => {
const email = req.body.email;
const password = req.body.password;
const student_num = req.body.student_num;
db.query(
"INSERT INTO student (email,passwordstudent_num) VALUES (?,?,?)",
[
email,
password,
student_num,
],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
}
}
);
});