赞
踩
基于antd的图片墙封装。
调用方法:
<PicturesWall maxNumber={1} showRemoveIcon={false}/>
效果:
代码:
- /**
- * 图片墙
- * 控件
- * @authors 缥缈潇潇
- * @date 2020-01-03
- */import React, {useState, useEffect} from 'react';
- import {Upload, message, Modal} from 'antd';
- import {RcFile, UploadFile} from "antd/lib/upload/interface";
- import './index.less';
- import {CommIcon} from '..';
- import {FileDownLoad, FileUpload} from "@/services/fileUploadService";
-
- interface ShowIcon {
- /**是否显示删除按钮*/
- showRemoveIcon?: boolean;
- /**是否显示预览按钮*/
- showPreviewIcon?: boolean;
- /**是否显示下载按钮*/
- showDownloadIcon?: boolean;
- }
-
- interface IProps {
- /**完成返回事件*/
- onChange?: (value: any) => void;
- /** 当前值,父组件为form时通过initialValue传入 */
- value?: any;
- /** 固定写死的初始值 */
- defaultValue?: any;
- /**业务名称,用于文件上传的时候区分业务类型,接口处可能用于区分文件归属文件夹*/
- businessName?: string;
- /**最大接受图片数量,默认10张*/
- maxNumber?: number;
- /**预览片样式*/
- style?: any;
- /**文件最大大小,默认2M*/
- maxSize?: number;
- /**按钮,默认全显示*/
- showIcon?: ShowIcon;
- }
-
- const PicturesWall = ({
- value, defaultValue, onChange, businessName, maxNumber = 10, style = {width: '100%'}, maxSize = 2, showIcon = {
- showRemoveIcon: true,
- showPreviewIcon: true,
- showDownloadIcon: true,
- }
- }: IProps) => {
- const [previewVisible, setPreviewVisible] = useState(false);
- const [fileList, setFileList] = useState(value || defaultValue || []);
- const [previewImage, setPreviewImage] = useState('');
-
- /**
- * 上传前事件
- * @param file 文件
- *
- * */
- const beforeUpload = (file: RcFile, fileList: RcFile[]) => {
- if (fileList.length > (maxNumber || 10)) {
- message.error('最多只能上传' + maxNumber + '张图片');
- return false;
- }
- let maxPicSize = maxSize ? maxSize : 2;
- const isJPG = file.type === 'image/jpg';
- const isPNG = file.type === 'image/png';
- const isJPEG = file.type === 'image/jpeg';
- if (!(isJPG || isPNG || isJPEG)) {
- message.error('只能上传jpg、png或者jpeg格式!');
- }
- const isLt = file.size / 1024 / 1024 < maxPicSize;
- if (!isLt) {
- message.error('最大只能上传' + maxPicSize + 'M大小的图片!');
- }
- return (isJPG || isPNG || isJPEG) && isLt;
- }
-
- /**
- * 关闭预览
- *
- * */
- const handleCancel = () => {
- setPreviewVisible(false)
- };
-
-
- /**
- * 打开预览
- * @param file 文件
- *
- * */
- const handlePreview = async (file: any) => {
- if (!file.url && !file.preview) {
- file.preview = file.thumbUrl;
- }
- setPreviewVisible(true);
- setPreviewImage(file.url || file.thumbUrl);
- };
-
- /**
- * 上传事件
- * @param info 返回参数
- *
- * */
- const handleChange = (info: any) => {
- let newFileList: any = [];
- const fileList = info.fileList;
- if (info.file.status) {
- if (info.file.status === 'done') {
- message.success(`${info.file.name} 上传成功`);
- } else if (info.file.status === 'error') {
- message.error(`${info.file.name} 上传失败`);
- }
- let ids = new Array<string>();
- let uploadOk = false;
- fileList.map((file: any) => {
- // 上传页面上传的
- if (file.response) {
- if (file.response.status === "200") {
- newFileList.push({
- ...file,
- id: file.response.entity.file_id,
- file_id: file.response.entity.file_id,
- path: file.response.entity.path,
- url: file.response.entity.path,
- thumbUrl: file.response.entity.path
- });
- ids.push(file.response.entity.file_id);
- uploadOk = true;
- }
- } else {
- // 编辑时回显的(回显时讲文件id查询出来放入uid字段)
- // 防止传递进来的列表中有id,返回后没有。
- newFileList.push({
- ...file,
- id: file.fileId,
- fileId: file.fileId,
- });
- ids.push(file.fileId);
- }
- });
- setFileList(newFileList);
- if (onChange && uploadOk) {
- onChange(ids.join(","));
- }
- }
- }
-
- const getUrl = async (fileIds: string) => {
- let files = new Array<any>();
- if (fileIds) {
- const ids = fileIds.split(",");
- for (let i = 0; i < ids.length; i++) {
- const res = await FileDownLoad({fileId: ids[i]});
- if (res.entity) {
- files.push({
- ...res.entity,
- name: res.entity.fileName,
- uid: ids[i],
- file_id: ids[i],
- url: res.entity.accessPath,
- path: res.entity.accessPath,
- thumbUrl: res.entity.accessPath,
- })
- }
- }
- }
- setFileList(files);
- }
- useEffect(() => { //加载图片
- getUrl(value || defaultValue || '');
- }, [value, defaultValue]);
- /**
- * 没有图片时候的显示图标
- * */
- const uploadButton = (
- <div style={{backgroundColor: "rgba(217, 217, 217, "}}>
- <CommIcon style={{fontSize: '30px', color: 'rgba(217, 217, 217, 1)'}} type={'iconimage'}/>
- </div>
- );
- return (
- <div className="clearfix picturesWall">
- <Upload
- name="uploadFile"
- listType="picture-card"
- accept='.jpg,.png,.jpeg'
- fileList={fileList}
- onPreview={handlePreview}
- onChange={handleChange}
- beforeUpload={beforeUpload}
- showUploadList={showIcon}
- multiple={false}
- customRequest={async (options: any) => {
- const formData = new FormData();
- formData.append('localFlag', "false");
- formData.append('privateFlag', "false");
- formData.append('uploadFile', options.file);
- formData.append('sysSign', process.env.sys_sign_no);
- formData.append('catalogNo', businessName || 'picWall');
- FileUpload('', formData).then((res: any) => {
- if (res.status === "200") {
- options.onSuccess(res, options.file)
- }
- })
- }}
- >
- {fileList.length >= maxNumber ? null : uploadButton}
- </Upload>
- <Modal visible={previewVisible} footer={null} onCancel={handleCancel}>
- <img alt="example" style={style} src={previewImage}/>
- </Modal>
- </div>
- );
- }
- export default React.memo(PicturesWall);
样式文件
:global {
.picturesWall {
.ant-upload-list-picture-card .ant-upload-list-item-thumbnail, .ant-upload-list-picture-card .ant-upload-list-item-thumbnail img {width: 100px !important;height: 100px !important;
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。