首页 > 其他分享 >react18中antd的Upload组件上传头像,并且拿到服务器返回的头像的url地址在页面中显示头像

react18中antd的Upload组件上传头像,并且拿到服务器返回的头像的url地址在页面中显示头像

时间:2023-04-22 14:55:21浏览次数:37  
标签:info const url memo Upload 头像 file 上传

业务需求:上传头像,上传完毕后拿到头像的url,把头像展示在页面中,最终把头像url和其他用户信息一起发送给服务器

 

上传头像流程

 

导入 Upload 组件和图标(一个加号,一个加载中)

import { Upload } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';

 

定义状态

const index = memo(() => {
  // 用于上传前和上传时切换
  const [loading, setLoading] = useState(false);

  // 用于保存服务端返回的头像url
  const [imageUrl, setImageUrl] = useState();
}

 

定义一个上传状态组件,上传前显示 + 号,上传时显示loading

const index = memo(() => {
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传
      </div>
    </div>
  );
}

 

组件代码(省略其他...)

const index = memo(() => {
  return (
    <Upload
      listType="picture-card" // 上传列表的内建样式
      showUploadList={false} // 是否展示文件列表
      action="" // 这里填写上传的地址
      beforeUpload={beforeUpload} // 上传前执行的操作
      onChange={handleChange} // 上传中、完成、失败都会调用这个函数。
      name='avatar' // 传递给后端的字段
    >
      {imageUrl ? (
        <img
          src={imageUrl}
          alt="avatar"
          style={{
            width: '100%',
          }}
        />
      ) :  (uploadButton)}
    </Upload>
  )
})

 

定义头像上传前执行的钩子函数

const index = memo(() => {
  // 该函数会在上传前执行,会把file对象传过来,可以对上传的文件类型判断,限制大小等
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 文件!');
    }
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('图片不能超过1MB!');
    }
    return isJpgOrPng && isLt1M;
  };
})

 

定义头像上传后执行的钩子函数

const index = memo(() => {
  const handleChange = (info) => {
      if (info.file.status === 'uploading') {
        setLoading(true);
        return;
      }
      // 当上传完毕
      if (info.file.status === 'done') {
          setLoading(false);
        // 判断是否上传成功
        if (info.file.response.code === 200) {
          // 把返回的图像地址设置给 imageUrl
          setImageUrl(info.file.response.data.imageUrl) // 取决于服务端返回的字段名
        }
      }
    };
})

 

以下是在控制台输出 info 对象

 

完整demo

import React, { memo, useState } from 'react'
import { UserWrapper } from './style'

import { Upload } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';

const index = memo(() => {

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 文件!');
    }
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('图片不能超过1MB!');
    }
    return isJpgOrPng && isLt1M;
  };

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      if (info.file.response.code === 200) {
        setLoading(false);
        setImageUrl(info.file.response.data.imageUrl)
      }
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传
      </div>
    </div>
  );
  
  return (
    <Upload
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action="上传的地址"
      beforeUpload={beforeUpload}
      onChange={handleChange}
      name='avatar'
    >
      {imageUrl ? (
        <img
          src={imageUrl}
          alt="avatar"
          style={{
            width: '100%',
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  )
})

export default index

标签:info,const,url,memo,Upload,头像,file,上传
From: https://www.cnblogs.com/zhanchujin/p/17343096.html

相关文章

  • web(XSS,CSRF,点击劫持,URL跳转)
    搜索被黑网站:关键字:Hackedby搜索引擎语法:Intitle:keyword标题中含有关键词的网页Intext:keyword正文中含有关键词的网页Site:domain在某个域名和子域名下的网页XSS全称:CrossSiteScript               中文名称:跨站脚本危害:盗取用户信息、钓鱼、......
  • Appuploader安装指南
    转载:http://kxdang.com/topic/appuploader/install.html下载和安装appuploaderIOS开发工具官网地址 http://www.applicationloader.net/最新版本已经优化了没支付688给apple的账号登录流程,无需再安装其他软件。部分电脑最新版本无法启动,请下载老版本。下载最新版本下载老版......
  • Appuploader证书申请教程
    转载:http://kxdang.com/topic/appuploader/certification.htmlIOS证书制作教程点击苹果证书按钮点击新增输入证书密码,名称这个密码不是账号密码,而是一个保护证书的密码,是p12文件的密码,此密码设置后没有其他地方可以找到,忘记了只能删除证书重新制作,所以请务必记住密码。还......
  • Appuploader证书申请教程
    转载:http://kxdang.com/topic/appuploader/certification.htmlIOS证书制作教程点击苹果证书按钮点击新增输入证书密码,名称这个密码不是账号密码,而是一个保护证书的密码,是p12文件的密码,此密码设置后没有其他地方可以找到,忘记了只能删除证书重新制作,所以请务必记住密码。还......
  • 《简化iOS APP上架流程,App Uploader助你搞定!》
    转载;http://kxdang.com/topic/appuploader/questions.htmlAppuploader常见错误及解决方法  问题解决秘籍遇到问题,第一个请登录苹果开发者官网检查一遍账号是否有权限,是否被停用,是否过期,是否有协议需要同意,并且在右上角切换账号后检查所有关联的账号是否工作正常,apple......
  • 《简化iOS APP上架流程,App Uploader助你搞定!》
    转载;http://kxdang.com/topic/appuploader/questions.htmlAppuploader常见错误及解决方法  问题解决秘籍遇到问题,第一个请登录苹果开发者官网检查一遍账号是否有权限,是否被停用,是否过期,是否有协议需要同意,并且在右上角切换账号后检查所有关联的账号是否工作正常,apple......
  • 获取url中参数具体值的方法
    我们常用的是用正则或者其他处理办法,这个这里不讲,主要想谈以下方法 1、如果给到的地址是完整的地址,比如 https://i.cnblogs.com/posts/edit?test=123那么,我们使用 newURL('https://i.cnblogs.com/posts/edit?test=123').searchParams.get('test') 即可获取到test对应的值......
  • 遇到的一个URL解析问题,以及解决方案
    问题抛出 如图中的HTTP接口,如果客户端通过/test/next/访问的时候,会进入到哪个处理方法中呢?答案是会走入第一个接口,springmvc会把next当做第一个接口的参数传进去,虽然在接口设计的时候可以通过参数校验或者数据校验来确保接口的功能正确,不过这种乌龙请求,springmv......
  • javasec(五)URLDNS反序列化分析
    这篇文章介绍URLDNS就是ysoserial中⼀个利⽤链的名字,但准确来说,这个其实不能称作“利⽤链”。因为其参数不是⼀个可以“利⽤”的命令,⽽仅为⼀个URL,其能触发的结果也不是命令执⾏,⽽是⼀次DNS请求。ysoserial打包成jar命令mvncleanpackage-DskipTests,刚刚入门所以用这条链作......
  • java 通过url下载附件并压缩zip
    publicFilezipAttachFile(StringfilePathDir,List<String>urlFileList,StringmemberId)throwsException{filePathDir="/home/file";FilezipFileDir=newFile(filePathDir);if(!zipFileDir.exists()){......