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

上传头像流程

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

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

定义状态

  1. const index = memo(() => {
  2.   // 用于上传前和上传时切换
  3.   const [loading, setLoading] = useState(false);
  4.  
  5.   // 用于保存服务端返回的头像url
  6.   const [imageUrl, setImageUrl] = useState();
  7. }

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

  1. const index = memo(() => {
  2. const uploadButton = (
  3. <div>
  4. {loading ? <LoadingOutlined /> : <PlusOutlined />}
  5. <div
  6. style={{
  7. marginTop: 8,
  8. }}
  9. >
  10. 上传
  11. </div>
  12. </div>
  13. );
  14. }

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

  1. const index = memo(() => {
  2. return (
  3. <Upload
  4. listType="picture-card" // 上传列表的内建样式
  5. showUploadList={false} // 是否展示文件列表
  6. action="" // 这里填写上传的地址
  7. beforeUpload={beforeUpload} // 上传前执行的操作
  8. onChange={handleChange} // 上传中、完成、失败都会调用这个函数。
  9. name='avatar' // 传递给后端的字段
  10. >
  11. {imageUrl ? (
  12. <img
  13. src={imageUrl}
  14. alt="avatar"
  15. style={{
  16. width: '100%',
  17. }}
  18. />
  19. ) : (uploadButton)}
  20. </Upload>
  21. )
  22. })

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

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

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

  1. const index = memo(() => {
  2. const handleChange = (info) => {
  3. if (info.file.status === 'uploading') {
  4. setLoading(true);
  5. return;
  6. }
  7. // 当上传完毕
  8. if (info.file.status === 'done') {
  9. setLoading(false);
  10. // 判断是否上传成功
  11. if (info.file.response.code === 200) {
  12. // 把返回的图像地址设置给 imageUrl
  13. setImageUrl(info.file.response.data.imageUrl) // 取决于服务端返回的字段名
  14. }
  15. }
  16. };
  17. })

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

完整demo

  1. import React, { memo, useState } from 'react'
  2. import { UserWrapper } from './style'
  3.  
  4. import { Upload } from 'antd';
  5. import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
  6.  
  7. const index = memo(() => {
  8.  
  9. const [loading, setLoading] = useState(false);
  10. const [imageUrl, setImageUrl] = useState();
  11.  
  12. const beforeUpload = (file) => {
  13. const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  14. if (!isJpgOrPng) {
  15. message.error('只能上传 JPG/PNG 文件!');
  16. }
  17. const isLt1M = file.size / 1024 / 1024 < 1;
  18. if (!isLt1M) {
  19. message.error('图片不能超过1MB!');
  20. }
  21. return isJpgOrPng && isLt1M;
  22. };
  23.  
  24. const handleChange = (info) => {
  25. if (info.file.status === 'uploading') {
  26. setLoading(true);
  27. return;
  28. }
  29. if (info.file.status === 'done') {
  30. if (info.file.response.code === 200) {
  31. setLoading(false);
  32. setImageUrl(info.file.response.data.imageUrl)
  33. }
  34. }
  35. };
  36.  
  37. const uploadButton = (
  38. <div>
  39. {loading ? <LoadingOutlined /> : <PlusOutlined />}
  40. <div
  41. style={{
  42. marginTop: 8,
  43. }}
  44. >
  45. 上传
  46. </div>
  47. </div>
  48. );
  49.  
  50. return (
  51. <Upload
  52. listType="picture-card"
  53. className="avatar-uploader"
  54. showUploadList={false}
  55. action="上传的地址"
  56. beforeUpload={beforeUpload}
  57. onChange={handleChange}
  58. name='avatar'
  59. >
  60. {imageUrl ? (
  61. <img
  62. src={imageUrl}
  63. alt="avatar"
  64. style={{
  65. width: '100%',
  66. }}
  67. />
  68. ) : (
  69. uploadButton
  70. )}
  71. </Upload>
  72. )
  73. })
  74.  
  75. export default index

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

  1. 关于本地使用antd的upload组件上传文件,ngnix报错405的问题

    使用阿里的ui框架antd的upload,会自动请求ngnix上面的一个路径,也就是action所在的位置,一直报错405 not allowed,后来经讨论,统一将action写成一个路径,后端对这 ...

  2. React antd如何实现<Upload>组件上传附件再次上传已清除附件缓存问题。

    最近在公司做React+antd的项目,遇到一个上传组件的问题,即上传附件成功后,文件展示处仍然还有之前上传附件的缓存信息,需要解决的问题是,要把上一次上传的附件缓存在上传成功或者取消后,可以进行清除 ...

  3. Ant Design Upload 组件上传文件到云服务器 - 七牛云、腾讯云和阿里云的分别实现

    在前端项目中经常遇到上传文件的需求,ant design 作为 react 的前端框架,提供的 upload 组件为上传文件提供了很大的方便,官方提供的各种形式的上传基本上可以覆盖大多数的场景,但是对 ...

  4. VUE -- iview table 组件 中使用 upload组件 上传组件 on render 事件不会触发问题

    碰到的问题是: upload 组件在 on中写的监听事件不会被触发 在 props 中来监听:==>

  5. vue watch 监听element upload组件上传成功返回的url列表

    因为 on-success 上传成功返回的是一个异步的结果....如果父组件需要这个结果的话 必须用watch 监听 然后里面建立一个 save()方法 save方法里面再调用接口 传需要的上传之后的 ...

  6. element-ui upload组件上传

    方法一: <el-table-column label="操作"> <template slot-scope="scope"> < ...

  7. 【antd Vue】封装upload图片上传组件(返回Base64)

    最近需要把上传的图片信息存储到数据库,以base64的方式,需要重新封装一下antd的upload组件 1. 使用方法 引入组件然后配置一下即可使用,配置项包括 defaultImageList,需要 ...

  8. ueditor1.3.6jsp版在struts2应用中上传图片报"未找到上传文件"解决方案

    摘要: ueditor1.3.6jsp版在struts2应用中上传图片报"未找到上传文件"解决方案 在struts2应用中使用ueditor富文本编辑器上传图片或者附件时,即使配置 ...

  9. 使用commons-fileUpload组件上传文件

    在近期的一个项目中有用到commons-fileUpload组件进行实现文件上传的功能(由于没用到框架),在使用的过程中有遇到一些问题,经过自己的琢磨也算顺利地将其解决了,在这里做个记录. 一.com ...

  10. asp 文件上传(ASPUpload组件上传)

    要实现该功能,就要利用一些特制的文件上传组件.文件上传组件网页非常多,这里介绍国际上非常有名的ASPUpload组件 1 下载和安装ASPUpload   要实现该功能,就要利用一些特制的文件上传组件 ...

随机推荐

  1. SpringMvc配置和原理

    运行原理 DispatcherServlet通过HandlerMapping在MVC的容器中找到处理请求的Controller,将请求提交给Controller,Controller对象调用业务层接口 ...

  2. 深入理解Linux系统调用

    1.系统调用号查询 我的学号位数是08,在64位调用表里可以查到对应的系统调用函数是__x64_sys_lseek 2.lseek函数 由于没用过该函数,所以先去了解一下这个函数的作用: 直白的说就是 ...

  3. 02 docker的基本用法

    本章内容 1.OCI 2.docker核心组件--Cgroup与runC 3.docker的架构 4.docker的基本操作 5.安装docker环境 6.创建第一个容器 6.docker容器的状态变 ...

  4. springboot中redis使用和工具

    application.properties #Redis相关配置 spring.data.redis.host=localhost #端口 spring.data.redis.port=6379 # ...

  5. tuxedo启动相关的知识

    tuxedo启动都要启动哪些服务? tuxedo常用命令有哪些? 参考链接: https://docs.oracle.com/cd/E13161_01/tuxedo/docs10gr3/rfcm/rf ...

  6. Github高效搜索方式

    Github高效搜索方式 文章目录 Github高效搜索方式 0.写在前面 1.常用的搜索功能 1.1 直接搜索 1.2 寻找指定用户|大小的仓库 1.3 搜索仓库 1.4 查找特定star范围的仓库 ...

  7. C++初识指针之一

    新手学习C/C++都跳不过去的地方,就是指针,用的话,确实好用,但是概念比较绕, 指针的通俗说法 1.简单的来说,就是说每一个变量,在电脑内都占一个地方,这个地方用一个16进掉的编号来进行标记,类似于 ...

  8. FIRE2023:殁亡漫谈

    FIRE2023:殁亡漫谈 读书的时候,想到殁亡,脑海涌出一则喜欢的遗言: 钱花完了,我走了.签名 如果可能牵涉到旁人(比如殁在旅馆里),就再立一则: 我的殁与店家无关. 签名 然后放下Kindle, ...

  9. Windows11右键改Win10

    Win11改Win10右键模式 1.以管理员身份运行CMD控制台 2.在控制台中输入下列代码后回车执行 reg add "HKCU\Software\Classes\CLSID\{86ca1 ...

  10. 手写深度比较isEqual函数

    function isObject(obj){ return typeof obj ==='object'&&obj!==null } functon isEqual(obj1,obj ...