How can I upload user profile photo with react nodejs and cloudinary

I am trying to create a method that make user can upload their profile image on website but i am having trouble with data and server. How can I send image upload from user to server?

Here is my profilesController.js in server:

   exports.updateUserProfile = async (req, res) => {
      const userId = req.session.passport.user.id;
      // This array will contain all the update functions to run.
      const updates = [];
    
      // If a gravatar url has not been generated, do it now.
      const pictureValue = gravatar.url(
        req.body.email,
        { s: "100", r: "pg", d: "retro" },
        true
      );
    
      const payload = {
        fullname: req.body.fullname,
        location: req.body.location,
        webpage: req.body.webpage,
        linkedin: req.body.linkedin,
        institution: req.body.institution,
        bio: req.body.bio,
        major: req.body.major,
        mergedTo: userId,
        picture: req.body.picture,
        skillone: req.body.skillone,
        skilltwo: req.body.skilltwo,
        skillthree: req.body.skillthree
      };
    
      const skillsPayload = [req.body.skillone];
      
      if (skillsPayload.lastIndexOf(req.body.skilltwo) === -1) {
        skillsPayload.push(req.body.skilltwo);
      } else {
        skillsPayload.push("");
      }
    
      if (skillsPayload.lastIndexOf(req.body.skillthree) === -1) {
        skillsPayload.push(req.body.skillthree);
      } else {
        skillsPayload.push("");
      }
    
      // Update user's general profile in database
      const updateOne = await models.User.update(payload, {
        where: {
          id: userId,
        },
      });
    }

and here is my profileAPI.js contain routes: 

const express = require("express");
const router = express.Router();
const { body, param } = require("express-validator");
const { catchErrors } = require("../errors/errorHandlers");
const multer = require('multer');
const uuidv4 = require('uuid/v4');

// const upload_dir = "./";

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'public');
  },
  filename: (req, file, cb) => {
    cb(null, `${uuidv4()}-${file.filename.toLowerCase}`);
  }
});

const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (
      file.mimetype == 'image/png' ||
      file.mimetype == 'image/jpg' ||
      file.mimetype == 'image/jpeg'
    ) {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
    }
  }
});

router.post(
  "/upload-profile",
  restrictedRoute,
  upload.single('profileImg'),
  checkData,
);

And moving to my front-end code here is UserCard.js:

const UserCard = ({ picture, name, userEmail, isVerified, }) => {
  const [selectedValue, setSelectedValue] = useState("a");
  const handleChange = (event) => {
    setSelectedValue(event.target.value);
  };

  const [uploadFile, setUploadFIle] = useState("");

  const changeProfileImage = (event) => {
    setUploadFIle(event.target.files[0]);
  };

  const uploadImage = (e) => {
    e.preventDefault();
    // create object of form data
    const formData = new FormData();
    formData.append("profileImage", uploadFile);
    formData.append('name', name);

    axios
    .post(`/upload-profile`, formData, {
       headers: {
         'Content-Type': "multipart/form-data"
       }
    })
    .then(() => console.log("success"))
    .catch(err => console.log(err));
  };

  return (
    <div className="avatar--icon_profile">
      <Card className="profile--card_container">
        <CardContent>
          {picture ? (
            <div>
              <Avatar
                src={picture}
                alt="Avatar"
                className="avatar--profile_image"
              />  
              <input
                type="file"
                name="profileImage"
                onChange={changeProfileImage}
              />  
              <button onClick={uploadImage}>Submit</button>
            </div>
          ) : (
            <AccountCircleIcon className="avatar--profile_image" />
          )}
       }

Can someone help me with this project? I really appreciate it. i am new to react



from Recent Questions - Stack Overflow https://ift.tt/3dbxbMy
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Network Error and Timeout on Authorize.net JS

Spring Elasticsearch Operations