首页 > 解决方案 > 如何创建用户上传头像功能

问题描述

我在我的项目中使用 nextjs 和 cloudinary-react:

这是我的用户信息: 在此处输入图像描述

这是我的上传功能代码库:

  const uploadImage = () => {
    const formData = new FormData();
    formData.append("file", imageSelected);
    formData.append("upload_preset", "teammateme");

    axios.post("https://api.cloudinary.com/v1_1/teammateme/image/upload", formData)
      .then((response) => {
        console.log(response);
      });
  };

return (     
<Card className="profile--card_container">
        <CardContent>
          {picture ? (
            <div>
              <Avatar
                src={picture}
                alt="Avatar"
                className="avatar--profile_image"
              />
              <input
                type="file"
                onChange={(event) => {
                  setImageSelected(event.target.files[0]);
                }}
              />
              <button onClick={uploadImage}>Submit</button>
            </div>
          ) : (
            <AccountCircleIcon className="avatar--profile_image" />
          )}
)

如何为用户头像制作上传图片?

更新的控制台: 在此处输入图像描述

标签: reactjscloudinary

解决方案


如果我理解正确,您正在尝试secure_url在成功上传到 Cloudinary 后获得返回。为此,您可以替换:

axios.post("https://api.cloudinary.com/v1_1/teammateme/image/upload", formData)
  .then((response) => {
    console.log(response);
  });

和:

axios.post("https://api.cloudinary.com/v1_1/teammateme/image/upload", formData)
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
    var url = data.secure_url;
  });

这将记录完整的 Cloudinary 响应,然后secure_url专门提取url变量中的响应。


推荐阅读