使用Ant Design的Upload上传删除预览照片,以及上传图片状态一直处于uploading的解决方法。

一、界面构建

  1、创建index父组件

import React from "react";
import { Form } from "antd";
import UploadComponent from "./UploadComponent";
export default () => {
  const [form] = Form.useForm();
  return (
    <Form
      form={form}
      initialValues={
        {
          'uploadPhoto': []
        }
      }
    >
      <Form.Item name="uploadPhoto">
        <UploadComponent />
      </Form.Item>
    </Form>
  );
};

  2、创建UploadComponent子组件

import React, { useState, useEffect } from "react";
import { Upload } from 'antd';
import { PlusOutlined } from "@ant-design/icons";
export default (props: any) => {
  console.log(props)
  const [fileList, setFileList] = useState<any>([])      //展示默认值
  const handleChange = ({ file, fileList }: any) => {};
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div className="ant-upload-text">Upload</div>
    </div>
  );
  return (
    <Upload
      listType="picture-card"
      fileList={fileList}
      onChange={handleChange}
      action={'这里是你上传图片的地址'}
    >
      {fileList.length >= 8 ? null : uploadButton}
    </Upload>
  );
};

  这样一个简单界面就构造完成了,通过打印子组件的props,我们可以看到,父组件给子组件通过prop传递了一个对象,该对象中有value:子组件的默认值,id:FormItem的name,onChange:onChange事件

  

注:1、Form表单以及Upload请参考Ant Design官方文档
  2、因后台返回数据格式不同,所以fileList的设置也不同,本文仅供参考。
  3、本文后台返回的数据格式为:[{id:id1,imgUrl:imgUrl1},...],上传图片成功后,返回的也是一个key值,string类型,比如:qwertyuidsa151sad

二、设置upload的fileList

  上传图片后,下次再进入该页面时,Form就会有initialValues默认值,此时upload就要展示默认值中的图片。

  fileList是一个数组,数组中是n个对象,每个对象都包含 uid:上传图片的idname:上传图片的名字status:上传图片的状态url:图片路径。想展示图片就必须要设置 uid,status,url。也可以在该对象中增加自己所需要。
  当子组件的props.value变化时,就需要更新fileList,使用useEffect即可。具体代码如下
useEffect(() => {
    if (props.value) {
      let newFileList = props.value.map((item: any) => {
        return {
          uid: item.id || item.uid,      //存在id时,使用默认的id,没有就使用上传图片后自动生成的uid
          status: 'done',            //将状态设置为done  
          url: 'https://image/'+item.imgUrl,  //这里是展示图片的url,根据情况配置
          imgUrl: item.imgUrl,  //添加了一个imgUrl,保存Form时,向后台提交的imgUrl,一个key值
        }
      })
      setFileList(newFileList)
    }
 }, [props])

三、触发父组件传递的onChange

  当子组件每次上传图片或者删除图片时,都需要触发父组件的Onchange事件,来改变Form表单的值。自定义一个triggerChange函数,上传成功或者删除图片时,通过triggerChange来触发onChange

  const triggerChange = (value: any) => {
    const onChange = props.onChange;  
    if (onChange) {
      onChange(value);        //将改变的值传给父组件
    }
  };

四、file常用的status

  1、uploading:上传中

  2、done:上传成功

  3、error:上传错误

  4、removed:删除图片

五、上传图片

  上传图片时,触发Upload的onChange事件

  const handleChange = ({ file, fileList }: any) => {
  //file:当前上传的文件
  //通过map将需要的imgUrl和id添加到file中 fileList = fileList.map((file: any) => { if (file.response) { file.id = file.uid; file.imgUrl = file.response.data.key  //请求之后返回的key } return file; }); if (file.status !== undefined) { if (file.status === 'done') { console.log('上传成功') triggerChange(fileList); } else if (file.status === 'error') { console.log('上传失败') } } }

  这样之后,会发现上传图片的状态一直是uploading状态,这是因为上传图片的onChange只触发了一次。

  解决方法:在onChange中始终setFileList,保证所有状态同步到 Upload 内

 const handleChange = ({ file, fileList }: any) => {
     //...上一段代码
   //最外层一直设置fileLsit setFileList([...fileList]); }

  这样就可以正常上传图片了。

六、删除图片

  删除图片时,file的status为removed。具体代码如下

  const handleChange = ({ file, fileList }: any) => {
   //...代码    else if (file.status === 'removed') { if (typeof file.uid === 'number') { //请求接口,删除已经保存过的图片,并且成功之后triggerChange triggerChange(fileList); } else { //只是上传到了服务器,并没有保存,直接riggerChange triggerChange(fileList); } }
  //...代码 }

七、预览图片

  1、Upload添加onPreview

<Upload
  onPreview={handlePreview}
 >
</Upload>

  2、增加Modal

<Modal
   visible={previewVisible}
   title='预览照片'
   footer={null}
   onCancel={() => setPreviewVisible(false)}
>
   <img alt="example" style={{ width: '100%' }} src={previewImage} />
</Modal>

  3、添加previewVisible以及previewImage

const [previewVisible, setPreviewVisible] = useState<boolean>(false);
const [previewImage, setPreviewImage] = useState<string>('');

  4、添加handlePreview函数

  const handlePreview = async (file: any) => {
    setPreviewImage(file.imgUrl);    //这个图片路径根据自己的情况而定
    setPreviewVisible(true);
  };

  这样,图片的上传,删除,预览功能都已经实现了。

八、完整代码

  1、index完整代码

import React from "react";
import { Form } from "antd";
import UploadComponent from "./UploadComponent";
export default () => {
  const [form] = Form.useForm();
  return (
    <Form
      form={form}
      initialValues={
        {
          'uploadPhoto': []
        }
      }
    >
      <Form.Item name="uploadPhoto">
        <UploadComponent />
      </Form.Item>
    </Form>
  );
};
index.tsx

  2、UploadComponent完整代码

import React, { useState, useEffect } from "react";
import { Upload, Modal } from 'antd';
import { PlusOutlined } from "@ant-design/icons";
export default (props: any) => {
  console.log(props)
  const [fileList, setFileList] = useState<any>([])
  const [previewVisible, setPreviewVisible] = useState<boolean>(false);
  const [previewImage, setPreviewImage] = useState<string>('');
  useEffect(() => {
    if (props.value) {
      let newFileList = props.value.map((item: any) => {
        return {
          uid: item.id || item.uid,
          status: 'done',
          url: 'url' + item.imgUrl,
          imgUrl: item.imgUrl,
        }
      })
      setFileList(newFileList)
    }
  }, [props])
  const handleChange = ({ file, fileList }: any) => {
    fileList = fileList.map((file: any) => {
      if (file.response) {
        file.id = file.uid;
        file.imgUrl = file.response.data.key
      }
      return file;
    });
    if (file.status !== undefined) {
      if (file.status === 'done') {
        console.log('上传成功')
        triggerChange(fileList);
      } else if (file.status === 'error') {
        console.log('上传失败')
      } else if (file.status === 'removed') {
        if (typeof file.uid === 'number') {
          //请求接口,删除已经保存过的图片,并且成功之后triggerChange
          triggerChange(fileList);
        } else {
          //只是上传到了服务器,并没有保存,直接riggerChange
          triggerChange(fileList);
        }
      }
    }
    setFileList([...fileList]);
  }
  const triggerChange = (value: any) => {
    const onChange = props.onChange;
    if (onChange) {
      onChange(value);
    }
  };
  const handlePreview = async (file: any) => {
    setPreviewImage(`url/${file.imgUrl}`);
    setPreviewVisible(true);
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div className="ant-upload-text">Upload</div>
    </div>
  );
  return (
    <div>
      <Upload
        listType="picture-card"
        fileList={fileList}
        onChange={handleChange}
        onPreview={handlePreview}
        action={'url'}
        headers={{
          'Duliday-Agent': '4',
          'Duliday-Agent-Version': (0x020000).toString(),
          'X-Requested-With': 'null',
          'token': 'token'
        }}
      >
        {fileList.length >= 8 ? null : uploadButton}
      </Upload>
      <Modal
        visible={previewVisible}
        title='预览照片'
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
};
UploadComponent.tsx

  

  

猜你喜欢

转载自www.cnblogs.com/minorf/p/12937413.html
今日推荐