multiple image uploading nodejs reactjs multer - mysql

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

Related

ReactJS Upload picture (multer), store in MySQL, then display it

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

Nodejs: Can't post a string filed and image on the same request with Express and Mysql

I am using mutler to upload image with post request and also string data.
When I upload only the image with Postman or React, it is working, but when I send also the strings, it shows this:
undefined
TypeError: Cannot read properties of undefined (reading 'filename')
The string got saved to MySQL but not the image.
That's my code for the Multer:
let storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/images/')
},
filename: (req, file, callBack) => {
const mimeExtension = {
'image/jpeg': '.jpeg',
'image/jpg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
}
callBack(null, file.originalname)
}
})
let upload = multer({
storage: storage,
fileFilter: (req, file, callBack) => {
// console.log(file.mimetype)
if (file.mimetype === 'image/jpeg' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/png' ||
file.mimetype === 'image/gif') {
callBack(null, true);
} else {
callBack(null, false);
req.fileError = 'File format is not valid';
}
}
});
And that's my post request:
router.post('/', upload.single('image'), async (req, res) => {
try {
if (!req.file) {
console.log("You didnt upload a picture for your project");
}
const { title, about_the_project, project_link, user_id } = req.body
const projectnum = await SQL(`INSERT into project(title,about_the_project,project_link,user_id)
VALUES('${title}','${about_the_project}','${project_link}',${user_id}) `)
console.log(projectnum.insertId);
console.log(req.file && req.file.filename)
let imagesrc = 'http://127.0.0.1:5000/images/' + req.file && req.file.filename
await SQL(`UPDATE project SET image = '${imagesrc}' WHERE projectid = ${projectnum.insertId}`)
res.send({ msg: "You add a new project" })
} catch (err) {
console.log(err);
return res.sendStatus(500)
}
})
On React that's the code:
const PostNewProject = async () => {
let formData = new FormData()
formData.append('image', imgsrc)
const res = await fetch(`http://localhost:5000/project`, {
headers: { 'content-type': 'application/json' },
method: "post",
body: JSON.stringify({ title, about_the_project, project_link, languages, user_id }),formData,
// credentials: "include"
})
const data = await res.json()
if (data.err) {
document.getElementById("err").innerHTML = data.err
} else {
console.log(data);
document.getElementById("err").innerHTML = data.msg
}
}
And the input for the image upload
<Input
type='file'
name='image'
sx={{ width: '25ch' }}
onChange={(e) => setImgsrc(e.target.files[0])}
/>
Thank you for your help!
You did not write a comma after the filename and before the callback function in the Multer.
I think you should check you exports too.

Unable to show blob url in "pdf-viewer" => "ng2-pdf-viewer" in Angular 10

I have an API which is returning uploaded file as blob. When I try to bind src with blob URL then it does not show anything, however, when I try to bind direct URL then it can show PDF file. Here is my code given below.
My TS code
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
},
(err: Error) => {
},
() => {
const blob: Blob = new Blob([this.tempBlob], { type: this.contentType });
const fileName: string ='ilvsna.pdf';
this.myBlobURL = URL.createObjectURL(blob);
}
);
}
HTML
<pdf-viewer [src]="myBlobURL"
[render-text]="true"
[original-size]="false"
style="width: 400px; height: 500px"
></pdf-viewer>
Note: if I set myBlobURL URL to 'https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf' then it can display
I think I have a solution for you. You can use ArrayBuffer. #N.F. Code is correct, however, you said that you got error in the line => this.pdfSrc = new Uint8Array(fileReader.result);
So, change the line into => this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);.Finally, your ts code should look like below=>
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
const fileReader = new FileReader();
fileReader.onload = () => {
this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);
};
fileReader.readAsArrayBuffer(this.tempBlob);
},
(err: Error) => {
}
);
}
Try this.
ts
pdfSrc: Uint8Array;
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
const fileReader = new FileReader();
fileReader.onload = () => {
this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);
};
fileReader.readAsArrayBuffer(this.tempBlob);
},
(err: Error) => {
}
);
}
html
<pdf-viewer [src]="pdfSrc"
[render-text]="true"
[original-size]="false"
style="width: 400px; height: 500px"
></pdf-viewer>
I resolve with window.URL.createObjectURL of my return blob file from service:
-- ts file
this.obuService.getObuDocument(obuId, fileId).subscribe(
(data: HttpResponse<Blob>) => {
const url = window.URL.createObjectURL(data.body);
this.src = url;
this.viewPDF = true;
}
);
-- service
getObuDocument(obuId: number, fileId: number): Observable<any> {
const options = {
observe: 'response' as 'body',
Accept: 'application/pdf',
responseType: 'blob' as 'blob'
};
return this.http.get(this.apiUrl + '/' + obuId + '/upload/' + fileId, options)
.pipe(catchError(err => { throw err; }));
}

Error In Multer When Trying To Upload A Image

Currently new to multer, so here's my problem:
I kept getting the MulterError: Unexpected field as the output when i try to POST the jpg image into mysql. Can anyone see whats the bug in my code? Currently im trying to make a error message when an image of more than 1MB is uploaded.
var multer = require('multer');
var path = require('path');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + new Date().toISOString() + '-' + path.extname(file.originalname));
}
});
var upload = multer({storage: storage});
// Endpoint 13 (EXTRA FEATURE 1)
const fileFilter = (req, file, callback) => {
if(file.mimetype === 'image/jpg') {
callback(null,true);
}
callback(null,false);
}
var uploadFromDesktop = multer({
storage:storage,
limits: {
fieldSize: 1024 * 1024
},
fileFilter: fileFilter
});
app.post("/upload/", upload.single('productImage'), (req, res, next) => {
uploadFromDesktop(req,res),(error) => {
console.log(error);
if (error) {
if (error.code === 'LIMIT_FILE_SIZE') {
} else {
res.status(500).send({ 'status': status, 'error':error})
}
} else {
var temp = req.file.path;
var file = uploadDir + req.file.originalname;
var source = fs.createReadStream(temp);
var destination = fs.createWriteStream(file);
source.pipe(destination);
fs.unlink(temp);
source.on('end',function () {
var result = {
'status': 'success',
'file': file
}
fs.chmod(file,0777);
res.send(result);
})
source.on('error', function (error) {
var result = {
'status': 'Fail',
'error': error
};
res.send(result);
})
}
}
})
Try with fileSize:
limits: {
fileSize: 2 * 1024 * 1024 // 2 MB}

I can't fetch react form

Hi I try to make simple contact from in react, but I stuck on fetch() method.
This is my code. I have no idea what is wrong.
FrontEnd
export default class ContactForm extends React.Component<IContactFormProps, any> {
constructor(props) {
super(props);
// local state
this.state = {
tl: new TimelineMax({paused: true, delay: 1}),
name: "",
email: "",
subject: "",
message: "",
sent: false,
}
this.handleOnSubmit = this.handleOnSubmit.bind(this);
this.handleClearForm = this.handleClearForm.bind(this);
this.handleChange = this.handleChange.bind(this);
this.startAnimation = this.startAnimation.bind(this);
}
handleOnSubmit(e) {
console.log("ContactForm->handleOnSubmit(e).");
e.preventDefault();
let formData = new FormData();
formData.append(name, this.state.name);
console.log("formData: " + formData);
fetch('/contact', {
method: 'POST',
body: formData
})
.then((response) => {
console.log("response: " + response);
console.log("response.ok: " + response.ok);
return response.json();
})
.then((responseJson) => {
console.log("responseJson: " + responseJson);
})
.catch((error) => {
console.log("error from fetch: " + error);
});
}
handleClearForm(e) {
console.log("ContactForm->handleClearForm(e).");
// e.preventDefault();
}
handleChange(event) {
const target = event.target;
const name = event.target.name;
const value = event.target.value;
this.setState({
[name]: value
});
// console.log("event.target.value: " + event.target.value);
// this.setState({value: event.target.value});
}
startAnimation() {
console.log("ContactForm->startAnimation().");
}
componentDidMount() {
this.startAnimation();
}
componentWillUnmount() {
}
render() {
return (
<form className="contact-form-cnt"
onSubmit={ this.handleOnSubmit }>
<div className="top-row">
<input type="text" name="name" placeholder="Name"
className="name" ref="name"
value={this.state.name} onChange={this.handleChange}/>
<input type="text" name="email" placeholder="Em#il"
className="email" ref="email"
value={this.state.email} onChange={this.handleChange}/>
</div>
<input type="text" name="subject" placeholder="Subject"
className="subject" ref="subject"
value={this.state.subject} onChange={this.handleChange}/>
<textarea name="message" placeholder="Write Your message here."
className="message" ref="message"
value={this.state.message} onChange={this.handleChange}></textarea>
<button type="submit" name="submit"
className="submit" ref="Send"
onClick={ this.handleClearForm }>Send</button>
</form>
);
};
};
BackEnd
'use strict';
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const winston = require('winston');
const distPath = path.join(__dirname, '../dist');
const indexFileName = 'index.html';
const app = express();
const PORT = process.env.PORT || 8080;
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(express.static(distPath));
app.get('*', (req, res) => res.sendFile(path.join(distPath, indexFileName)));
app.post("/contact", (req, res) => {
try {
console.log("mail sending succes!");
}
catch ( error ) {
console.log("mail sending failure!");
}
});
app.listen(PORT, (err) => {
if (err) {
winston.error(err);
return;
}
winston.info(`Listening on port ${PORT}`);
});
URL:
http://localhost:8080/contact
and error
POST http://localhost:8080/contact 404 (Not Found)
I think it's something with url, but I'am out of ideas. Any sugestions?
try something like this:
app.post("/contact", (req, res) => {
res.json({"foo": "bar"});
});
this way you are setting an json object as result. Let me know if works.