Im using reactJs,
Im working in localhost.
I managed to upload the picture,
Impossible to display the picture after the upload.
I managed to show the post data but not the picture
Here how I tried to display the picture :
{/* <img src="./16644430197124927082.png" alt='postimage'/> */}
{/* <img src={`${SERVER}`} alt="postimage"/> */}
{/* <img src={`${req.protocol}://${req.get('host')}/images/16644430197124927082.png`} /> */}
<div> <img src={val.image} alt="postphoto" /> </div>
Post.js (to get the data)
const express = require('express')
const router = express.Router()
const db = require('../config/db')
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { resolve } = require('path');
var storage = multer.diskStorage({
destination: 'client/src/images/',
filename: function (req, file, callback) {
callback(null, Date.now() + file.originalname);
}
});
var upload = multer({ storage: storage });
router.post('/upload', upload.single("file"), function (req, res, file) {
console.log(req.file, req.body);
const post = req.body.name;
const image = `${req.protocol}://${req.get('host')}/src/images/${req.file.filename}`;
console.log(image);
const username = req.body.username;
db.query(
"INSERT INTO post (post, image, username) VALUES (?, ?, ?);", [post, image, username],
(err, results) => {
console.log(err);
res.send(results);
}
);
});
router.get("/", (req, res) => {
db.query(
"SELECT * FROM socialmedia.post;",
(err, results) => {
console.log(err);
res.send(results);
}
);
});
Home.js (to display the data)
function Home() {
const [uploads, setUploads] = useState([]);
const [likes, setLikes] = useState([]);
useEffect(() => {
if (!localStorage.getItem("loggedIn")) {
localStorage.setItem("loggedIn", false);
}
}, []);
const getData = () => {
Axios.get("http://localhost:3001/post").then((response) => {
setUploads(response.data);
// response.data.map((val)=> {
// setLikes([...likes, val.likes]);
// });
});
console.log(likes);
}
useEffect(() => {
if (localStorage.getItem("loggedIn") === "true") {
getData(); } else {
alert("vous devez ĂȘtre connectĂ© pour afficher ce contenu!");
window.location.href = "/login";
}
}, []);
const likePost = (id) => {
Axios.post("http://localhost:3001/post/like", { userLiking: localStorage.getItem('username'), postid: id }).then((response) => {
console.log("You liked this post", response);
getData();
});
};
const editPost = (id) => {
window.location.href = `/edit/${id}`;
console.log(id);
};
return (
<div className='home'>
{uploads.map((val) => {
return (
<div className='post'>
<div className='user'>{val.username}</div>
<div className='content'>{val.post}</div>
{/* <img src="./16644430197124927082.png" alt='postimage'/> */}
{/* <img src={`${SERVER}`} alt="postimage"/> */}
{/* <img src={`${req.protocol}://${req.get('host')}/images/16644430197124927082.png`} /> */}
<div> <img src={val.image} alt="postphoto" /> </div>
<ThumbUpAltIcon
id="likeButton"
onClick={() => {
likePost(val.id);
}}
/>
{val.likes}
<button onClick={() => {
editPost(val.id);
}}>modifier ce post</button>
{/* <div><img src="./../images/1665482108659ae7dcd7bcb1861f88999f1277775df23.jpg" alt="postphoto" /> </div> */}
</div>
)
})}
</div>
)
};
export default Home
Related
I'm trying to make a upload image feature in my website. I've worked on uploading a single image and it worked how do I change my code to make it upload multiple images at same time code below:
Server Side:
// img storage confing
var imgconfig = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, "./uploads");
},
filename: (req, file, callback) => {
callback(null, `image-${Date.now()}.${file.originalname}`)
}
});
// img filter
const isImage = (req, file, callback) => {
if (file.mimetype.startsWith("image")) {
callback(null, true)
} else {
callback(null, Error("only image is allowd"))
}
}
var upload = multer({
storage: imgconfig,
fileFilter: isImage
})
// register userdata
app.post("/insertImage", upload.single("photo"), (req, res) => {
const { filename } = req.file;
console.log(req.file)
});
Client Side:
const [file, setFile] = useState("");
const setimgfile = (e) => {
setFile(e.target.files[0])
}
const addUserData = async (e) => {
e.preventDefault();
var formData = new FormData();
formData.append("photo", file)
const config = {
headers: {
"Content-Type": "multipart/form-data"
}
}
const res = await Axios.post("/insertImage", formData, config);
if (res.data.status == 201) {
console.log("NO error")
} else {
console.log("error")
}
}
REACT JSX
Here is my input file and multiple is added here
What should i do?? Please help me
<div style={{ padding: 15, backgroundColor: '#fff', marginTop: 15 }}>
<h4>Upload file:</h4>
<input type="file" name='photo' onChange={setimgfile} multiple/>
<button onClick={addUserData}>submit</button>
</div>
UI:
const [files, setFile] = useState("");
const setimgfile = (e) => {
setFile(e.target.files)
}
const addUserData = async (e) => {
e.preventDefault();
var formData = new FormData();
for (const file of files) {
formData.append('files', file)
}
const config = {
headers: {
"Content-Type": "multipart/form-data"
}
}
const res = await Axios.post("/insertImage", formData, config);
if (res.data.status == 201) {
console.log("NO error")
} else {
console.log("error")
}
}
<div style={{ padding: 15, backgroundColor: '#fff', marginTop: 15 }}>
<h4>Upload file:</h4>
<input type="file" name='photo' onChange={setimgfile} multiple />
<button onClick={addUserData}>submit</button>
</div>
BACKEND:
import multer from 'multer';
const storage = multer.diskStorage({
destination: (req, file, cb) => {
// Uploaded files destination
cb(null, "uploads/");
},
filename: (req, file, cb) => {
const newFilename = `${new Date().getDate()}-${new Date().getMonth() + 1}-${new Date().getFullYear()}-${file.originalname}`;
cb(null, newFilename);
}
});
const upload = multer({ storage }).array('files');
app.post("/insertImage", upload, (req, res) => {
console.log('success')
});
I've been trying to figure this out for hours, but i think im doing it wrong. So what im basically doing is.
-> Fetch the specific user, and throw it into the placeholder -> which is working
but when I try to edit the information and then when i try to save it this error shows and then in my phpadmin, it saves a null. it seems that I can't connect the front and the backend.
sql: 'UPDATE users SET name = NULL, email = NULL, mobile = NULL WHERE id = ${id} '
Edit.jsx
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
const EditUser = () => {
const navigate = useNavigate()
const [data, setData] = useState([])
const [inputs, setInputs] = useState([])
const { id } = useParams()
useEffect(() => {
const getUser = async () => {
const res = await axios.get(`http://localhost:5000/${id}`)
setData(res.data[0])
}
getUser()
}, [])
const handleSubmit = async () => {
try {
await axios.put(`http://localhost:5000/${id}`, inputs)
} catch (error) {
console.log(error)
}
}
const handleChange = (e) => {
setInputs({ ...inputs, [e.target.name]: e.target.value })
}
return (
<div>
<form
action=""
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
}}
onSubmit={handleSubmit}
>
<label htmlFor="">Name</label>
<input type="text" placeholder={data.name} onChange={handleChange} />
<label htmlFor="">Email</label>
<input type="text" placeholder={data.email} onChange={handleChange} />
<label htmlFor="">Mobile</label>
<input type="text" placeholder={data.mobile} onChange={handleChange} />
<button type="submit">save</button>
</form>
</div>
)
}
export default EditUser
backend.js
app.put('/:id', (req, res) => {
const id = req.params.id
const name = req.body.name
const email = req.body.email
const mobile = req.body.mobile
pool.query(
`UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ${id} `,
[name, email, mobile],
(err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
}
)
})
app.get('/:id', (req, res) => {
const { name, email, mobile } = req.body
const { id } = req.params
pool.query(`SELECT * FROM users WHERE id = ${id} `, (err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
})
})
May be you should try :
The following states :
const EditUser = () => {
const navigate = useNavigate()
const [data, setData] = useState([])
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [mobile, setMobile] = useState("")
const { id } = useParams()
For your request :
const handleSubmit = async () => {
let datas ={
name: name,
email: email,
mobile: mobile
}
try {
await axios.put('http://localhost:5000/updateUser/'+id, datas)
} catch (error) {
console.log(error)
}
}
Then you just update your states that way :
<form
action=""
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
}}
onSubmit={handleSubmit}
>
<label htmlFor="">Name</label>
<input type="text" placeholder={data.name} onChange={()=>
{setName(e.currentTarget.value)} />
<label htmlFor="">Email</label>
<input type="text" placeholder={data.email} onChange={()=>
{setEmail(e.currentTarget.value)} />
<label htmlFor="">Mobile</label>
<input type="text" placeholder={data.mobile} onChange={()=>
{setMobile(e.currentTarget.value)} />
<button type="submit">save</button>
</form>
For you back end maybe you should add some informations in the adress (to avoid confusion with you app.get):
app.put('updateUser/:id', (req, res) => {
const id = req.params.id
const name = req.body.name
const email = req.body.email
const mobile = req.body.mobile
pool.query(
`UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ${id} `,
[name, email, mobile],
(err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
}
)
})
I hope it will help you !
I think I did it actually, but I dont know if this is the right method. so what i did is
instead of directing submit it as an await
const handleSubmit = async () => {
try {
await axios.put(`http://localhost:5000/${id}`, inputs)
} catch (error) {
console.log(error)
}
}
i did this.
const handleSubmit = async (e) => {
e.preventDefault()
try {
const res = await axios.put(`http://localhost:5000/${id}`, inputs)
setInputs(res.data)
} catch (error) {
console.log(error)
}}
Hey guys, if its wrong, please show me the other way.
I'm working currently on a website where a user should be able to upload an image.
But unfortunately I get this error: GET c:\fakepath\nfr.jpeg net::ERR_UNKNOWN_URL_SCHEME
I'm using Express and multer.
Here's the code for my backend:
const storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/') // './public/images/' directory name where save the file
},
filename: (req, file, callBack) => {
callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
const upload = multer({
storage: storage
})
app.get('/api/get', (req, res) => {
db.query(
'SELECT * FROM users',
(err, result) => {
if (err) {
console.log(err)
}
res.send(result)
}
)
})
app.post('/api/create', (upload.single('image')), (req, res) => {
const title = req.body.title
const post = req.body.post
const imagesrc = req.body.image
db.query(
'INSERT INTO users (title, post_text, images) VALUES (?,?,?)', [title, post, imagesrc],
(err, result) => {
if (err) {
console.log(err)
}
console.log(result)
}
)
})
Here's my code for the frontend:
const [title, setTitle] = useState('')
const [post, setPost] = useState('')
const [image, setImage] = useState('')
const submitPost = () => {
axios.post('http://localhost:3001/api/create', {
title: title,
post: post,
image: image,
}).then(r => {
console.log(r)
}).catch(err => {
console.log(err)
})
}
const [postList, setPostList] = useState([])
useEffect(() => {
axios.get('http://localhost:3001/api/get').then((data) => {
console.log(data)
setPostList(data.data)
})
}, [])
<div className="createPost">
<input
type='file'
name='file'
onChange={(e) => {
setImage(e.target.value)
}}
/>
<img src={image}/>
<input
type="text"
placeholder="Titel"
onChange={(e) => {
setTitle(e.target.value)
}}
/>
<input
type="text"
placeholder="Post"
onChange={(e) => {
setPost(e.target.value)
}}
/>
</div>
<div className="postButton">
<button onClick={submitPost}>speichern</button>
</div>
<div className="post">
{postList.map((val, key) => {
return (
<div className="Post" key={key}>
<h1>{val.title}</h1>
{/*<p>{val.username}</p>*/}
<p>{val.post_text}</p>
<p>{val.image}</p>
<button className="kaufenButton" onClick={toggleModalUnt}>Jetzt testen</button>
</div>
)
})}
</div>
If you need anything else, let me know it.
Thanks in advance.
hope you are fine.
I am stuck at my university group project.
I have mysql database in which I have tables which contains images, images in database are stored in BLOB data type. Now I want to convert BLOB into images and display it in my web page.Any help would be greatly appreciated.
My code is below (logic.js) :
import React from 'react'
import {useState, useEffect} from "react"
import Axios from 'axios';
import { Col, Card, Row, Button } from 'antd';
import 'antd/dist/antd.css';
import Buttonfilter from './Button';
const Logic = () => {
const { Meta } = Card;
const [foodList, setfoodList] = useState([]);
const [clothesList, setclothesList] = useState([]);
const [techList, settechList] = useState([]);
const [Limit, setLimit] = useState(8);
const [buttons, setButtons] = useState([])
let [data, setData] = useState([])
let [filter, setFilter] = useState([])
useEffect(() => {
Axios.get('http://localhost:3001/api/get/food').then((response) => {
setfoodList(response.data);
});
}, []);
useEffect(() => {
Axios.get('http://localhost:3001/api/get/clothes').then((response) => {
setclothesList(response.data);
});
}, []);
useEffect(() => {
Axios.get('http://localhost:3001/api/get/tech').then((response) => {
settechList(response.data);
});
}, []);
data = [...foodList, ...clothesList, ...techList]
const onLoadMore = () => {
setLimit(Limit + 8);
}
let handleToggle = (link) => {
console.log(link)
return (<a href = {link}/>)
}
// //{<a href = {val.Link}>{URL.createObjectURL(val.Image)}</a>}
let renderDefaultCards = data.slice(0, Limit).map((val, index) => {
return <Col key={index} lg={6} md={8} xs={24}>
<Card
onClick={() => handleToggle(val.Link)}
hoverable={true}
cover = {<a href = {val.Link} />}
>
<Meta
title={val.Company}
description={val.Description}
/>
</Card>
</Col>
})
let renderCards = filter.slice(0, Limit).map((val, index) => {
return <Col key={index} lg={6} md={8} xs={24}>
<Card
onClick={() => handleToggle(val.Link)}
hoverable={true}
cover = {<a href = {val.Link} />}
>
<Meta
title={val.Company}
description={val.Description}
/>
</Card>
</Col>
})
//style={{ display: 'flex', height: '300px', justifyContent: 'center', alignItems: 'center' }}
return (
<div style = {{ width : '75%', margin: '3rem auto' }}>
<div style = {{ textAlign: 'center' }}>
<h2>Eco Friendly Companies </h2>
</div>
{/* {filter} */}
<Button type = 'primary' onClick={() => {
setFilter(data)
}}>All</Button>
<Button onClick={() => {
setFilter(foodList)
}}>Food</Button>
<Button onClick={() => {
setFilter(clothesList)
}}>Clothes</Button>
<Button onClick={() => {
setFilter(techList)
}}>Tech</Button>
<br></br>
<br></br>
<br></br>
{filter.length === 0 ?
<div >
<Row gutter={[16, 16]}>
{renderDefaultCards}
</Row>
</div> :
<div>
<Row gutter={[16, 16]}>
{renderCards}
</Row>
</div>
}
<br></br>
<div style = {{ display: 'flex', justifyContent: 'center'}}>
<button onClick={onLoadMore}>Load More</button>
</div>
</div>
)
}
export default Logic
here's server side code using node js
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors');
//connectivity with database
const db = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'ecoFriendly'
});
//Making middleware to reduce expected errors.
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
//get request for data stored in Food table in database
app.get('/api/get/food', (req,res) => {
const sql = "SELECT * from Food";
db.query(sql, (err, result) => {
res.send(result);
});
});
//get request for data stored in Clothes table in database
app.get('/api/get/clothes', (req,res) => {
const sql = "SELECT * from Clothes";
db.query(sql, (err, result) => {
res.send(result);
});
});
// //get request for data stored in Tech table in database
app.get('/api/get/tech', (req,res) => {
const sql = "SELECT * from Tech";
db.query(sql, (err, result) => {
res.send(result);
});
});
app.listen(3001, () => {
console.log("running on port 3001");
});
I'm working on a recipe site using API from a third party and want to change the number of servings (which is output from the API data) when clicking the + & - button. I tried assigning the output serving amount <Servings>{recipe.servings}</Servings> in a variable and useState to update it but it kept showing errors. I would appreciate any help (preferably using react Hooks). Thanks :)
Here is my code:
const id = 716429;
const apiURL = `https://api.spoonacular.com/recipes/${id}/information`;
const apiKey = "34ac49879bd04719b7a984caaa4006b4";
const imgURL = `https://spoonacular.com/cdn/ingredients_100x100/`;
const {
data: recipe,
error,
isLoading,
} = useFetch(apiURL + "?apiKey=" + apiKey);
const [isChecked, setIsChecked] = useState(true);
const handleChange = () => {
setIsChecked(!isChecked);
};
return (
<Section>
<h2>Ingredients</h2>
<ServingsandUnits>
{recipe && (
<ServingsIncrementer>
<p>Servings: </p>
<Minus />
<Servings>{recipe.servings}</Servings>
<Plus />
</ServingsIncrementer>
)}
<ButtonGroup>
<input
type="checkbox"
id="metric"
name="unit"
checked={isChecked}
onChange={handleChange}
/>
<label htmlFor="male">Metric</label>
</ButtonGroup>
</ServingsandUnits>
</Section>
};
My custom hook is called useFetch:
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
fetch(url, { signal: abortCont.signal })
.then((res) => {
if (!res.ok) {
// error coming back from server
throw Error("Could not fetch the data for that resource");
}
return res.json();
})
.then((data) => {
setIsLoading(false);
setData(data);
setError(null);
})
.catch((err) => {
if (err.name === "AbortError") {
console.log("Fetch aborted");
} else {
// auto catches network / connection error
setIsLoading(false);
setError(err.message);
}
});
return () => {
abortCont.abort();
};
}, [url]);
return { data, isLoading, error };
};
export default useFetch;