How to Add Image Upload for Mean Stack Blog
I'm currently learning the MERN stack by making a project, one of this project'due south functionalities is to create a user profile, by doing and so I needed to implement a file input in the form in order to add together the user's profile pic, and this is where I got stuck! the process of uploading a photo seemed complicated but don't worry I figured out (hence the championship).
Setting up the project
Within the project's folder, I made two folders: frontend and backend
| |-- project | |-- frontend |-- backend
Setting up the frontend role
First cd into the frontend folder
cd frontend
Then set up up your react app
npx create-react-app .
we're as well going to upload the axios package which is a promise-based HTTP client for the browser and node.js.
npm i axios
Now let's become to coding, create a User.js component in the src folder.
the data that we're sending to the server includes name, nascence engagement, and a photo that could only be a png, jpg, or jpeg.
import React , { useState } from ' react ' ; import axios from ' axios ' ; const User = () => { const [ newUser , setNewUser ] = useState ( { name : '' , birthdate : '' , photo : '' , } ); const handleSubmit = ( east ) => { e . preventDefault (); const formData = new FormData (); formData . append ( ' photo ' , newUser . photograph ); formData . append ( ' birthdate ' , newUser . birthdate ); formData . append ( ' name ' , newUser . proper noun ); axios . post ( ' http://localhost:5000/users/add/ ' , formData ) . and so ( res => { console . log ( res ); }) . catch ( err => { console . log ( err ); }); } const handleChange = ( e ) => { setNewAuthor ({... newUser , [ due east . target . name ]: e . target . value }); } const handlePhoto = ( e ) => { setNewAuthor ({... newUser , photo : east . target . files [ 0 ]}); } return ( < grade onSubmit = { handleSubmit } encType = 'multipart/course-information' > < input blazon = "file" take = ".png, .jpg, .jpeg" name = "photograph" onChange = { handlePhoto } /> < input type = "text" placeholder = "proper noun" name = "name" value = { newUser . name } onChange = { handleChange } /> < input type = "engagement" name = "birthdate" value = { newUser . date } onChange = { handleChange } /> < input type = "submit" /> </ form > ); } consign default User ;
Import the User component inside App.js
import ' ./App.css ' ; import ' ./User ' ; role App () { return ( < User /> ); } export default App ;
Setting up the backend part
In the backend binder, we need to upload the needed packages:
npm i express cors mongoose multer uuid
Here's the reason why we need these packages:
- express: is a minimalist spider web framework for node
- cors: is a node.js package for providing a Connect/Express middleware that can exist used to enable CORS with various options, according to the cors package repository
- mongoose: Mongoose is a MongoDB object modeling tool designed to piece of work in an asynchronous environment.
- multer: is a node.js middleware for handling multipart/grade-information.
- uuid: is a bundle that generates random and unique ids, I apply it in this project to make sure that every uploaded paradigm has a unique name.
create app.js
const express = require ( ' express ' ); const cors = require ( ' cors ' ); const mongoose = require ( ' mongoose ' ); const app = express (); crave ( ' dotenv ' ). config (); const port = process . env . PORT || 5000 ; app . utilise ( cors ()); app . use ( limited . json ()); const uri = procedure . env . ATLAS_URI ; mongoose . connect ( uri , { useNewUrlParser : truthful , useCreateIndex : true , useUnifiedTopology : true }); const connection = mongoose . connection ; connection . once ( ' open ' , () => { console . log ( ' mongo DB success ' ); }); const userRouter = crave ( ' ./routes/users ' ); app . use ( ' /users ' , userRouter ); app . listen ( port , () => { panel . log ( `Example app listening at http://localhost: ${ port } ` ) })
Create .env file and store in information technology the port and your atlas URI.
Make a routes folder and create user.js inside it; also create the images folder inside the backend binder.
const router = crave ( ' express ' ). Router (); const multer = crave ( ' multer ' ); const { v4 : uuidv4 } = require ( ' uuid ' ); let path = require ( ' path ' ); permit User = require ( ' ../models/user.modal ' ); const storage = multer . diskStorage ({ destination : function ( req , file , cb ) { cb ( null , ' images ' ); }, filename : function ( req , file , cb ) { cb ( null , uuidv4 () + ' - ' + Date . now () + path . extname ( file . originalname )); } }); const fileFilter = ( req , file , cb ) => { const allowedFileTypes = [ ' paradigm/jpeg ' , ' paradigm/jpg ' , ' image/png ' ]; if ( allowedFileTypes . includes ( file . mimetype )) { cb ( null , true ); } else { cb ( nix , false ); } } let upload = multer ({ storage , fileFilter }); router . route ( ' /add ' ). mail ( upload . single ( ' photograph ' ), ( req , res ) => { const name = req . body . name ; const birthdate = req . body . birthdate ; const photograph = req . file . filename ; const newUserData = { name , birthdate , photo } const newUser = new User ( newUserData ); newUser . save () . then (() => res . json ( ' User Added ' )) . catch ( err => res . status ( 400 ). json ( ' Fault: ' + err )); }); module . exports = router ;
and don't forget to brand the user.modal.js in the modals folder
const mongoose = require ( ' mongoose ' ); const Schema = mongoose . Schema ; const userSchema = new Schema ({ proper noun : { blazon : String , required : true , trim : true }, photo : { type : Cord }, birthdate : { type : Cord } }); const User = mongoose . model ( ' User ' , userSchema ); module . exports = User ;
And that's it! that's how you upload an prototype to the server.
Source: https://dev.to/yosraskhiri/how-to-upload-an-image-using-mern-stack-1j95
0 Response to "How to Add Image Upload for Mean Stack Blog"
Enregistrer un commentaire