Created
May 30, 2021 15:55
-
-
Save vimal-verma/af9aac9d0558704b1ce1a86407a43d08 to your computer and use it in GitHub Desktop.
MERN File upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// client | |
import React, {useState} from 'react' | |
import axios from 'axios' | |
export default function Image() { | |
const [Image, setImage] = useState('Choose File'); | |
const [ImageUrl, setImageUrl] = useState('Choose File'); | |
const handleSubmit = (e) => { | |
e.preventDefault(); | |
const formData = new FormData(); | |
formData.append('avatar', Image); | |
axios.post(`/upload`,formData) | |
.then(res =>{ | |
console.log(res) | |
setImageUrl(res.data.url) | |
}) | |
.catch(err => { | |
console.log(err) | |
}) | |
}; | |
return ( | |
<form onSubmit={handleSubmit}> | |
<input type="file" name="image" onChange={e=>setImage(e.target.files[0] )} required /> | |
<button type="submit">Add</button> | |
</form> | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// server | |
const express = require('express'); | |
const mongoose = require('mongoose'); | |
require('dotenv').config() | |
var cors = require('cors') | |
const cloudinary = require("cloudinary").v2; | |
var multer = require('multer') | |
var upload = multer({ dest: 'uploads/' }) | |
// mongodb setup | |
const dbURI = process.env.DB_URL; | |
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true }) | |
.then(result => console.log('connected to db')) | |
.catch(err => console.log(err)); | |
const app= express(); | |
app.use(express.json()) | |
app.use(cors()) | |
cloudinary.config({ | |
cloud_name: process.env.CLOUDINARY_CLOUD_NAME, | |
api_key: process.env.CLOUDINARY_API_KEY, | |
api_secret: process.env.CLOUDINARY_API_SECRET | |
}); | |
app.post('/profile',upload.single('avatar'),(req,res)=>{ | |
console.log(req.file) | |
cloudinary.uploader.upload(req.file.path) | |
.then((result) => { | |
console.log(result) | |
res.status(200).send({ | |
uploaded: "true", | |
url : result.url | |
}); | |
}) | |
.catch((error) => { | |
console.log(error) | |
res.status(404).send({error}); | |
}); | |
}) | |
const port = process.env.PORT || 5000 | |
app.listen(port, console.log(`app is running on port ${port}, go to http://localhost:${port}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you forgot to add this.
axios.defaults.baseURL = http://localhost:5000