Ant design pro常用(8):上传图片

components/FileUpload/index.tsx(创建组件)

import React, { Component } from 'react'
import {Form,Upload,Modal,notification} from 'antd';
import axios from 'axios'
import {connect} from 'dva'
import {getUserID} from '@/utils/memory'
import {PlusOutlined} from '@ant-design/icons'
import config from '@/utils/config'
const tailLayout = {
    wrapperCol: { span:8 },
};
const uploadButton= (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
)
const mapState=({constants})=>{
    const {token} = constants;
    return {token} //获取token值
}
const {uploadURL,uploadType} = config;//获取上传图片的地址
@connect(mapState)
class FileUpload extends Component {
     state={
        fileList:[],//上传图片的数组
        files:[],//给后台传递图片的id
        previewVisible: false,//查看图片
        previewImage: '',
        previewTitle: '',
    };
     componentDidMount(){
        this.getTokenHandle();//获取token的函数
        const {newFiles,newOrEdit} = this.props;//传递的参数
        if(newOrEdit==='edit'){
            //渲染filesList
            if(newFiles.length){
                let files = newFiles.map(item => { return item.id })
                this.setState({fileList:newFiles,files})
            }   
        }
    };
    render() {
        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        return (
            <div>
               <Form.Item label='上传附件' {...tailLayout}>
                        <Upload
                            onPreview={this.handlePreview}
                            listType="picture-card"
                            onChange={this.fileUploadChange}
                            defaultFileList={fileList}
                            multiple = {this.props.multiple }
                            onRemove={this.removeFileHandle}
                            
                            >
                            {fileList.length >= 8 ? null : uploadButton}
                        </Upload>      
                    </Form.Item> 
                    <Modal
                        visible={previewVisible}
                        title={previewTitle}
                        footer={null}
                        onCancel={this.handleCancel}
                        >
                        <img alt="example" style={{ width: '100%' }} src={previewImage} />
                    </Modal>
            </div>
        )
    };
    //获取token
    getTokenHandle(){
        const {dispatch} = this.props;
        if(dispatch){
            dispatch({
                type:'constants/uploadTokenEffect'
            })
        }
    };
    //删除图片
    removeFileHandle = (file)=>{
        const {dispatch} = this.props;
        const {id} = file;
        const index = this.state.files.findIndex(item=>item===id);
        this.state.files.splice(index,1);
        if(dispatch){
            dispatch({
                type:'constants/removeFileEffect',
                payload:file.id
            })
        }
    };
    //转成base64
    getBase64(file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => resolve(reader.result);
          reader.onerror = error => reject(error);
        });
      };
      //预览图片
      handlePreview = async file => {
        if (!file.url && !file.preview) {
          file.preview = await this.getBase64(file.originFileObj);
        }
    
        this.setState({
          previewImage: file.url || file.preview,
          previewVisible: true,
          previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
      };
      //关闭弹出框
       handleCancel = () => this.setState({ previewVisible: false });
       //上传图片改变
        fileUploadChange =({file,fileList})=>{
            //图片上传成功的操作
            if(file.status==='done'){
                let url = uploadURL + this.props.token;//获取上传图片地址
                let userID = getUserID();//获取用户的id
                this.setState({ fileList: [...fileList] });//filesList赋值
                //接口需要的参数(不同的接口,所需要的参数不同)
                const formData = new FormData();
                formData.append('x:type',uploadType.adv);
                formData.append('x:owner','');
                formData.append('x:creator',userID);
                formData.append('x:target','');
                fileList.forEach((file:any)=>{
                    formData.set('file',file.originFileObj)
                })
                const config = {
                    headers: { 'Content-Type': 'multipart/form-data' }
                }
                //ajax请求接口
                axios.post(url,formData,config).then(res=>{
                    //返回数据
                    let files =[...this.state.files,res.data.data];
                    this.setState({files},()=>{
                        //将图片的id,添加到filesList,以便于删除
                        this.state.fileList.forEach((item,index)=>{
                            item['id']= this.state.files[index]
                        })
                    });[图片的id1,图片的id2,...]
                    
                    if(this.state.fileList.length === this.state.files.length){
                        notification.success({
                            message:'上传成功'
                        })
                        this.props.fileChange(this.state.files);//将[图片的id1,图片的id2,...]传出去
                    }
                })
            }
    };
 }

组件使用

import FileUpload from '@/component/FileUpload';
class operateComponent extends Component {
    //selectItem调用接口返回要修改的对象
    //newOrEdit是判断新建(create)还是编辑(edit)
    render(){
        const {selectItem} = this.props;
        return (
            <Form>
                <FileUpload 
                        fileChange={this.fileChangeHandle} 
                        newOrEdit={this.props.newOrEdit} 
                        newFiles={selectItem.files && selectItem.files.length?selectItem.files:[]}/>
            </Form>
        )
    };
    fileChangeHandle =(value:any)=>{
        this.setState({files:value})
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值