首页 > 其他分享 >带回显的图片上传组件

带回显的图片上传组件

时间:2023-02-27 18:34:30浏览次数:48  
标签:const upload value ant item 带回 file 组件 上传

 

 

 

import React, { useState, Fragment, useMemo } from 'react';
import { Upload, Modal, Progress } from 'antd';
import { proxyDCIMAPI } from '@/services/proxyAPI';
import { runInAction } from 'mobx';
import {
    updateFile,
    deleteFile,
} from '@/services/commonAPI/updateFile';
import { helper, checkType } from '@/utils/T';
import Prompt from '@/utils/prompt';
import Viewer from 'react-viewer';
import patrolDataStore from '@/pages/PatrolEnter/model/patrolDataStore';
const { DCIM_DownloadZip, getFileName } = helper;

const DoUpload = (props) => {
    const { item, value, onChange, handSave, isErrorUpload, ...rest } = props;
    const {
        EnumAcceptType = '',
        EnumAcceptTypeArray = [],
        EnumAcceptPicType = '',
        EnumAcceptPicTypeArray = [],
    } = window.DCIMAPP;
    const [visible, setVisible] = React.useState(false);
    const [isShow, setIsShow] = React.useState('');
    const { assetId, id, isDisabled } = rest;
    const { saveComponentConf } = patrolDataStore;
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');

    const [fileList, setFileList] = useState(value || []);
    const [percent, setPercent] = useState(0);
    const [percentShow, setPercentShow] = useState(false);
    const { disabled, size, count, isOnlyPicture, ...otherProps } =
        item?.['x-props'];
    const [uploadLoading, setLoading] = useState(true);
    const beforeUpload = (file) => {
        const isLtSize = file.size / 1024 / 1024 < size;
        if (!isLtSize && size) {
            Prompt.error(
                window.intl.formatMessage({
                    id: 'DoFprmSchema.components.DoUpload.FileSize',
                    defaultMessage: '文件大小超出限制!',
                })
            );
            return false;
        }
        if (!validFileType(file)) {
            Prompt.error(
                window.intl.formatMessage({
                    id: 'DoFprmSchema.components.DoUpload.FileFormat',
                    defaultMessage: '文件格式不符合上传要求!',
                })
            );
            return false;
        }
    };

    const validFileType = (file) => {
        const fileType = isOnlyPicture
            ? EnumAcceptPicTypeArray
            : EnumAcceptTypeArray;
        const suffix = file.name.split('.')[file.name.split('.').length - 1];
        const bo = fileType.includes(file.type) || fileType.includes(suffix); //
        return bo;
    };

    const customRequest = ({
        file,
        onProgress,
        onSuccess,
        one rror,
        ...rest
    }) => {
        try {
            const handleFile = (item) => {
                const res = {
                    name: item.fileName,
                    uid: helper.guid(),
                    status: 'done',
                    url: `${item.url}`,
                };
                return res;
            };

            const cb = (event) => {
                setPercent(((event.loaded / event.total) * 100).toFixed(2));
                setLoading(false);
            };

            if (beforeUpload(file)) return false;
            else {
                // percentChange(file.size)
                setPercentShow(true);
                updateFile({ file }, cb).then(
                    (resp) => {
                        onSuccess(resp, file);
                        const _file = handleFile(resp.data);
                        const newFileList = fileList.concat(_file);

                        setPercentShow(false);
                        setPercent(0);
                        setFileList(newFileList);
                        onChange?.(newFileList);
                        handSave?.(newFileList);
                        !isErrorUpload &&
                            saveComponentConf?.(
                                { default: newFileList },
                                assetId,
                                item.key
                            );
                        setLoading(true);
                    },
                    (error) => {
                        Prompt.error(
                            window.intl.formatMessage({
                                id: 'DoFprmSchema.components.DoUpload.UploadFailed',
                                defaultMessage: '上传失败,请重新选择文件',
                            })
                        );
                        setPercentShow(false);
                        setPercent(0);
                        one rror();
                    }
                );
            }
        } catch (error) {
            console.error(error);
        }
    };

    const onDownloadHandle = (value) => {
        let params = {
            filename: value.name ?? value.url,
        };
        DCIM_DownloadZip(proxyDCIMAPI('/inspection/plan/download'), {
            method: 'get',
            params,
        })
            .then(
                (res) =>
                    runInAction(() => {
                        if (res) {
                            handleExport(res);
                        }
                    }),
                (res) =>
                    runInAction(() => {
                        Prompt.error(res.msg);
                    })
            )
            .catch((err) => console.error(err));
    };
    const handleExport = (res) => {
        const iframe = document.createElement('a');
        let url = window.URL.createObjectURL(new Blob([res.data]));
        let fileName = '';
        fileName = getFileName(fileName, res);
        iframe.download = fileName;
        iframe.href = url;
        document.querySelector('body')?.appendChild(iframe);
        iframe.click();
        document.querySelector('body')?.removeChild(iframe);
    };

    const onPreviewPic = (value) => {
        if (checkType.isPicType(value?.name ?? value?.url)) {
            // setPreviewImage(value.url);
            // setPreviewVisible(true);
            showImg(value?.url);
        } else {
            Prompt.warn(
                window.intl.formatMessage({
                    id: 'DoFprmSchema.components.DoUpload.PreviewNot',
                    defaultMessage: '该文件不支持预览!',
                })
            );
        }
    };
    const handleCancel = () => {
        setPreviewVisible(false); //todo: 暂无使用可去除
    };

    const onRemoveHandle = (value) => {
        // if(uploadLoading)
        deleteFile(value.name).then(
            (resp) => {
                const _fileList = fileList.filter(
                    (item) => item.uid != value.uid
                );
                setFileList(_fileList);
                Prompt.success(
                    window.intl.formatMessage({
                        id: 'message.deleted.label',
                        defaultMessage: '删除成功',
                    })
                );
                onChange?.(_fileList);
                handSave?.(_fileList);
                !isErrorUpload &&
                    saveComponentConf?.(
                        { default: _fileList },
                        assetId,
                        item.key
                    );
            },
            (error) => {
                Prompt.error(error.msg);
                // one rror();
            }
        );
    };

    //实现放大缩图片
    const showImg = (src) => {
        setIsShow(src);
        setVisible(true);
        helper.setDisplay('block');
    };
    return (
        <div className="doUpload">
            <Fragment>
                <Viewer
                    visible={visible}
                    onClose={() => {
                        helper.setDisplay('none');
                        setVisible(false);
                    }}
                    images={[{ src: isShow, alt: '' }]}
                />
                <Upload
                    accept={isOnlyPicture ? EnumAcceptPicType : EnumAcceptType}
                    listType="picture-card"
                    disabled={isDisabled}
                    // 移动端上传的没有uid填充
                    fileList={(fileList ?? []).map((file) => ({
                        ...file,
                        uid: file.uid ?? file.url,
                        status: 'done',
                    }))}
                    beforeUpload={(file) => beforeUpload(file)}
                    customRequest={customRequest}
                    onPreview={(value) => onPreviewPic(value)}
                    onDownload={(value) => onDownloadHandle(value)}
                    onRemove={(value) => onRemoveHandle(value)}
                    showUploadList={{
                        showDownloadIcon: true,
                        showRemoveIcon: uploadLoading,
                    }}
                >
                    {count && fileList.length >= count ? null : (
                        <div className="upload-btn">
                            {percentShow ? (
                                <Progress
                                    className="progress-line"
                                    percent={Number(percent)}
                                    size="small"
                                    showInfo={false}
                                    status="active"
                                />
                            ) : (
                                <div className="ant-upload-text">
                                    {window.intl.formatMessage({
                                        id: 'common.upload',
                                        defaultMessage: '上传',
                                    })}
                                    {count ? (
                                        <span>
                                            ({fileList.length}/{count})
                                        </span>
                                    ) : null}
                                </div>
                            )}
                        </div>
                    )}
                </Upload>
                <Modal
                    visible={previewVisible}
                    // title={previewTitle}
                    footer={null}
                    onCancel={handleCancel}
                >
                    <img
                        alt="example"
                        style={{ width: '100%' }}
                        src={previewImage}
                    />
                </Modal>
            </Fragment>

            {/*language=SCSS*/}
            <style jsx>{`
                .doUpload {
                    :global(.ant-upload-list-item-name) {
                        display: block !important;
                        position: absolute;
                        bottom: 3px;
                        z-index: 99;
                        padding: 3px;
                        color: #63a7f9;
                    }
                    :global(.ant-upload-list-picture
                            .ant-upload-list-item-icon, .ant-upload-list-picture-card
                            .ant-upload-list-item-icon) {
                        top: 39%;
                    }
                    // height: 78px;
                    :global(.ant-upload-list-picture-card-container) {
                        height: 75px;
                        width: 75px;
                    }
                    :global(.ant-upload-list-picture-card
                            .ant-upload-list-item) {
                        height: 75px;
                        width: 75px;
                        font-size: 12px;
                    }
                    :global(.CM_DB-upload.CM_DB-upload-select-picture-card) {
                        width: 75px;
                        height: 75px;
                    }
                    :global(.ant-upload-list-picture
                            .ant-upload-list-item, .ant-upload-list-picture-card
                            .ant-upload-list-item) {
                        padding: 0;
                    }
                    :global(.doUpload.jsx-629672960
                            .ant-upload.ant-upload-select-picture-card) {
                        position: relative;
                    }
                    .fileList-length {
                        display: inline-block;
                    }
                    .upload-btn {
                        position: relative;
                    }
                    :global(.ant-progress-line) {
                        position: absolute;
                        bottom: -15px;
                        left: 50%;
                        transform: translateX(-50%);
                    }
                }
            `}</style>
        </div>
    );
};

export default DoUpload;

 

标签:const,upload,value,ant,item,带回,file,组件,上传
From: https://www.cnblogs.com/Simoon/p/17161415.html

相关文章

  • SREWorks前端低代码组件生态演进:monorepo架构重构和远程组件加载实践
    作者:王威(地谦)文章结构项目背景演进分析monorepo架构演进Webpack与Rollup如何平滑迁移构建优化组件的可扩展与可插拔演进总结版本动态项目背景SREWorks是一个面向企业级复杂......
  • react封装图片上传组件
    支持表单受控和非受控使用,基于antdupload进行的二次封装,使用场景如下图: 1.组件文件夹  2.index.tsx贴代码importReact,{useEffect,useMemo,useState}f......
  • 上传gitlab代码后jenkins自动进行发布的配置
     1、安装​​GitLabPlugin​​​和​​GenericWebhookTriggerPlugin​​两个插件2、要在gitlab生成一个访问api的token 3、在jenkins的系统管理里找到下面界面进行输......
  • formdesigner支持jeecgboot的部门与人员组件
      根据网友tom提供的代码,集成了formdesigner支持jeecgboot的部门与人员组件。1、人员组件在formdesigner组件的items下建立userList.js/***用户组件*/exportletus......
  • Vue组件是怎样挂载的
    我们先来关注一下$mount是实现什么功能的吧:我们打开源码路径core/instance/init.js:exportfunctioninitMixin(Vue:Class<Component>){......initLifec......
  • VUE里父组件与子组件的交互操作
        在开发vue前端项目时,经常会遇到父组件与子组件之间的相互操作,比如有时候父组件需要知道子组件的触发事件,以便对这个触发事件进行响应,同时附组件也要传递数据给子......
  • Go组件库总结之介入式链表
    本篇文章我们用Go封装一个介入式的双向链表,目的是将链表的实现和具体元素解耦。文章参考自:https://github.com/brewlin/net-protocol1.元素的接口typeElementinterface......
  • vue源码分析-动态组件
    前面花了两节的内容介绍了组件,从组件的原理讲到组件的应用,包括异步组件和函数式组件的实现和使用场景。众所周知,组件是贯穿整个Vue设计理念的东西,并且也是指导我们开发的......
  • #甘特图# DHTMLXGantt 组件笔记
    配置配置缩放单位gantt.config.scale,示例gantt.config.scale=[{unit:"day",step:1,format:"%d%M"}]需要注意的是,当显示比较小的刻度如天、小时甚至时分钟......
  • 组件内路由守卫
    简介:作用:给组件设置权限beforeRouteEnter(to,from,next){通过路由规则,进入该组件时被调用},beforeRouteLeave(to,from,next){通过路由规则,离开该组件时被调用},......