无法使用 cloudinary 更新个人资料图片

Posted

技术标签:

【中文标题】无法使用 cloudinary 更新个人资料图片【英文标题】:Can't update the profile picture using cloudinary 【发布时间】:2021-12-15 02:37:39 【问题描述】:

我尝试在 Cloudinary 中上传一张图片,并希望将其保存到我的数据库中。在 Cloudinary 中上传图像工作正常,但我无法将其保存到我的数据库中。每当我尝试这样做时,它只使用我在模型中设置的默认图像。也喜欢 setPic 正在工作,但它一次又一次地更改为默认图像。请任何人帮我解决这个问题。

如果您需要任何其他详细信息,请发表评论。请帮帮我。

这里是函数

const postDetails = (pics) => 
    setPicMessage(null);
    if (pics?.type === 'image/jpeg' || pics?.type === 'image/png') 
      const data = new FormData();
      data.append('file', pics);
      data.append('upload_preset', 'codeblogger_profile_image');
      data.append('cloud_name', 'dhuej17x0');
      fetch('https://api.cloudinary.com/v1_1/dhuej17x0/image/upload', 
        method: 'post',
        body: data,
      )
        .then((res) => res.json())
        .then((data) => 
          setPic(data.secure_url.toString());
          console.log(pic);
        )
        .catch((err) => 
          toast.error(err);
        );
     else 
      setPicMessage('Please Select an Image');
      toast.error(picMessage);
    
  ;

这是完整的 Profile.js 文件

import React,  useEffect, useState  from 'react';
import  Button, Col, Container, Form, InputGroup, Row  from 'react-bootstrap';
import  toast, ToastContainer  from 'react-toastify';
import  useDispatch, useSelector  from 'react-redux';
import  getUserDetails, updateUserProfile  from '../actions/userActions';
import  USER_UPDATE_PROFILE_RESET  from '../constant/userConstants';

const Profile = ( history ) => 
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [pic, setPic] = useState();
  const [password, setPassword] = useState('');
  const [picMessage, setPicMessage] = useState();
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordType, setPasswordType] = useState('password');
  const [passwordType2, setPasswordType2] = useState('password');
  const [showPass, setShowPass] = useState(false);
  const [showPass2, setShowPass2] = useState(false);

  const dispatch = useDispatch();

  const userDetails = useSelector((state) => state.userDetails);
  const  user  = userDetails;

  // console.log(` this is from line 25 $user`);

  const userLogin = useSelector((state) => state.userLogin);
  const  userInfo  = userLogin;

  const userUpdateProfile = useSelector((state) => state.userUpdateProfile);
  const  success  = userUpdateProfile;

  useEffect(() => 
    if (!userInfo) 
      history.push('/login');
     else 
      if (!user || !user.name || success) 
        dispatch( type: USER_UPDATE_PROFILE_RESET );
        dispatch(getUserDetails('profile'));
       else 
        setName(user.name);
        setEmail(user.email);
        setPic(user.pic);
      
    

    if (success) 
      toast.success('Profile Updated successfully');
    
    showPass ? setPasswordType('text') : setPasswordType('password');
    showPass2 ? setPasswordType2('text') : setPasswordType2('password');
  , [showPass, showPass2, dispatch, history, success, user, userInfo]);

  const postDetails = (pics) => 
    setPicMessage(null);
    if (pics?.type === 'image/jpeg' || pics?.type === 'image/png') 
      const data = new FormData();
      data.append('file', pics);
      data.append('upload_preset', 'codeblogger_profile_image');
      data.append('cloud_name', 'dhuej17x0');
      fetch('https://api.cloudinary.com/v1_1/dhuej17x0/image/upload', 
        method: 'post',
        body: data,
      )
        .then((res) => res.json())
        .then((data) => 
          setPic(data.secure_url.toString());
          console.log(pic);
        )
        .catch((err) => 
          toast.error(err);
        );
     else 
      setPicMessage('Please Select an Image');
      toast.error(picMessage);
    
  ;

  const submitHandler = (e) => 
    e.preventDefault();
    if (password !== confirmPassword) 
      toast.error('Passwords do not match');
     else 
      dispatch(updateUserProfile( id: user._id, name, email, password ));
    
  ;

  return (
    <div className="profilePage mt-4 py-3">
      <ToastContainer />
      <Container>
        <h2>PROFILE</h2>
        <Row className="profileContainer">
          <Col md=6>
            <Form onSubmit=submitHandler>
              <Form.Group controlId="name" className="mb-2">
                <Form.Label>Name</Form.Label>
                <Form.Control
                  type="text"
                  value=name
                  placeholder="Name"
                  onChange=(e) => setName(e.target.value)
                />
              </Form.Group>
              <Form.Group controlId="email" className="mb-2">
                <Form.Label>Email</Form.Label>
                <Form.Control
                  type="email"
                  placeholder="Email"
                  value=email
                  onChange=(e) => setEmail(e.target.value)
                />
              </Form.Group>
              <Form.Group controlId="password" className="mb-2">
                <Form.Label>New Password</Form.Label>
                <InputGroup>
                  <Form.Control
                    type=passwordType
                    placeholder="New Password"
                    value=password
                    onChange=(e) => setPassword(e.target.value)
                  />
                  <InputGroup.Text>
                    <i
                      onClick=() => setShowPass(!showPass)
                      className=showPass ? 'fas fa-eye-slash' : 'fas fa-eye'
                      style= cursor: 'pointer' ></i>
                  </InputGroup.Text>
                </InputGroup>
              </Form.Group>
              <Form.Group controlId="confirmPassword" className="mb-2">
                <Form.Label>Confirm Password</Form.Label>
                <InputGroup>
                  <Form.Control
                    type=passwordType2
                    placeholder="Confirm Password"
                    value=confirmPassword
                    onChange=(e) => setConfirmPassword(e.target.value)
                  />
                  <InputGroup.Text>
                    <i
                      onClick=() => setShowPass2(!showPass2)
                      className=showPass2 ? 'fas fa-eye-slash' : 'fas fa-eye'
                      style= cursor: 'pointer' ></i>
                  </InputGroup.Text>
                </InputGroup>
              </Form.Group>
              <Form.Group controlId="pic" className="mb-2">
                <Form.Label>Change Profile Picture</Form.Label>
                <Form.Control
                  onChange=(e) => postDetails(e.target.files[0])
                  type="file"
                  accept=".jpeg,.png,.jpg"
                  custom="true"
                />
              </Form.Group>
              <Button
                type="submit"
                variant="success"
                style= letterSpacing: '2px' >
                UPDATE
              </Button>
            </Form>
          </Col>
          <Col
            style=
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            >
            <img src=pic alt=user.name className="profilePic" />
          </Col>
        </Row>
      </Container>
    </div>
  );
;

export default Profile;

【问题讨论】:

【参考方案1】:

在 submitHandler 方法中,您没有在 updateUserProfile 中传递 pic 变量。

使用这个

dispatch(updateUserProfile( id: user._id, name, email, password, pic ));

【讨论】:

我发现了我刚刚忘记添加这个作为答案的缺陷。

以上是关于无法使用 cloudinary 更新个人资料图片的主要内容,如果未能解决你的问题,请参考以下文章

cloudinary java无法上传图片

Carrierwave Cloudinary 集成 Ruby on Rails

Cloudinary 上传图像小部件无法按预期工作

无法使用 Heroku 将图像上传到 Cloudinary

获取 Facebook 图像并将其上传到 Elastic Beanstalk 中的 S3 或 Cloudinary

如何将特定的 json 响应对象设置为 js var - Cloudinary