react antd上传图片视频pdf

antd上传附件分为图片视频文件,我封装成一个组件供使用,以下有几个案例,根据如下进行匹配:
组件:

import './index.less';

import { FileTextOutlined, PlusOutlined } from '@ant-design/icons';
import { useMemoizedFn } from 'ahooks';
import { Empty, Image, message, Upload, UploadProps } from 'antd';
import { RcFile } from 'antd/lib/upload';
import { UploadFile } from 'antd/lib/upload/interface';
import deploy from 'config';
import _ from 'lodash';
import React, { useState } from 'react';
import { getToken } from 'utils';

interface Props extends UploadProps {
  fileType?: 'img' | 'office' | 'pdf';
}
const index: React.FC<Props> = React.memo(({ className, fileType, ...props }) => {
  const [previewUrl, setPreviewUrl] = useState<string | undefined>();

  const handleBeforeUpload = useMemoizedFn((file: RcFile, FileList: RcFile[]) => {
    if (fileType === 'pdf') {
      if (!file.type.includes('application/pdf')) {
        message.info({ content: '请正确的选择PDF', className: 'ant-message-custom no-icon' });
        return Upload.LIST_IGNORE;
      }
    }
    if (fileType === 'img') {
      if (!file.type.includes('image/')) {
        message.info({ content: '请正确的选择图片', className: 'ant-message-custom no-icon' });
        return Upload.LIST_IGNORE;
      }
    }
    if (fileType === 'office') {
      if (!file.type.includes('application/vnd.openxmlformats') && !file.type.includes('application/vnd.ms')) {
        message.info({ content: '请正确的选择文档', className: 'ant-message-custom no-icon' });
        return Upload.LIST_IGNORE;
      }
    }

    return true;
  });
  const handlePreview = useMemoizedFn(async (file: UploadFile<any>) => {
    if (file.preview) {
      setPreviewUrl(file.preview);
    } else if (file.thumbUrl) {
      setPreviewUrl(file.thumbUrl);
    } else if (file.originFileObj) {
      let previewUrl = file.preview ?? (await getBase64(file.originFileObj));

      if (previewUrl) setPreviewUrl(previewUrl as string);
    }
  });

  return (
    <>
      <Upload
        className={`ant-upload-file ${className ?? ''}`}
        action={`${deploy.SERVER_URL}/datafile/upload`}
        headers={{ Authorization: `${getToken()}` }}
        listType="picture-card"
        {..._.omit(props, ['value', 'defaultValue'])}
        onChange={(info) => {
          const { file } = info;

          if (file.error) {
            file.error = {
              statusText: '上传失败',
              message: '上传失败',
            };
          }
          if (file.response?.message && typeof file.response?.message === 'string') {
            file.error = {
              statusText: file.response?.message,
              message: file.response?.message,
            };
            message.error(file.response?.message);
            file.response.message = undefined;
          }

          props.onChange && props.onChange(info);
        }}
        onPreview={props.onPreview ?? handlePreview}
        beforeUpload={fileType ? handleBeforeUpload : props.beforeUpload}
      >
        {props.children ?? (
          <div className="ant-upload-button-card">
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>上传</div>
          </div>
        )}
      </Upload>
      <span style={{ display: 'none' }}>
        <Image
          preview={{ src: previewUrl, visible: Boolean(previewUrl), onVisibleChange: () => setPreviewUrl(undefined) }}
        />
      </span>
    </>
  );
});

/// get Img file Base64
function getBase64(file: RcFile) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

export default index;

export const FileSelectBox: React.FC<{
  image?: React.ReactNode;
  description?: string;
  height?: string | number;
  width?: string | number;
  style?: React.CSSProperties;
}> = React.memo((props) => {
  return (
    <div className="ant-upload-file-slect-box" style={{ width: props.width, height: props.height, ...props.style }}>
      <Empty
        image={props.image ?? <FileTextOutlined />}
        imageStyle={{ height: 20 }}
        description={props.description ?? '选择文件'}
      />
    </div>
  );
});

使用图片:

<FileUpload
              fileType="img"
              style={{ width: '100%' }}
              maxCount={3}
              defaultFileList={props?.record?.imageList.map((e) => ({
                uid: e.id,
                name: e.name,
                fileName: e.name,
                status: 'done',
                type: 'image/jpeg',
                response: { id: e.id },
                thumbUrl: `${deploy.SERVER_URL}/datafile/download?dataFileId=${e.id}&token=${getToken()}`,
              }))}
              onChange={(info) => {
                let ids: string[] = info.fileList.filter((o) => o.status === 'done').map((o) => o.response['id']);

                props.form.setFieldsValue({ images: ids });
              }}
              children={
            	<div className="ant-upload-button-card">
      			<FileJpgOutlined style={{ fontSize: 40 }} />
     			<div style={{ marginTop: 8 }}>选择图片</div>
    			</div>
    }
            />

使用pdf:

<FileUpload
              fileType="pdf"
              style={{ width: '100%' }}
              showUploadList={{
                showPreviewIcon: false,
              }}
              defaultFileList={props?.record?.constructionDrawingsList.map((e) => ({
                uid: e.id,
                name: e.name,
                fileName: e.name,
                status: 'done',
                type: 'application/pdf',
                response: { id: e.id },
              }))}
              onChange={(info) => {
                let ids: string[] = info.fileList.filter((o) => o.status === 'done').map((o) => o.response['id']);

                props.form.setFieldsValue({ constructionDrawings: ids });
              }}
              children={
				<div className="ant-upload-button-card">
     			<FilePdfOutlined style={{ fontSize: 40 }} />
      			<div style={{ marginTop: 8 }}>选择PDF</div>
    			</div>
}
            />

视频上传也如上述如此。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用 Ant Design 的 Upload 组件来实现图片上传功能。首先,需要安装 Ant Design: ``` npm install antd ``` 然后,在你的 React 组件中引入 Upload 组件: ```jsx import { Upload, message } from 'antd'; import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'; class Avatar extends React.Component { state = { loading: false, imageUrl: '' }; handleChange = info => { if (info.file.status === 'uploading') { this.setState({ loading: true }); return; } if (info.file.status === 'done') { // Get this url from response in real world. getBase64(info.file.originFileObj, imageUrl => this.setState({ imageUrl, loading: false, }), ); } }; render() { const { loading, imageUrl } = this.state; const uploadButton = ( <div> {loading ? <LoadingOutlined /> : <PlusOutlined />} <div className="ant-upload-text">Upload</div> </div> ); return ( <Upload name="avatar" listType="picture-card" className="avatar-uploader" showUploadList={false} action="https://www.mocky.io/v2/5cc8019d300000980a055e76" beforeUpload={beforeUpload} onChange={this.handleChange} > {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton} </Upload> ); } } ``` 这个例子中,我们定义了一个 Avatar 组件,其中包含一个 Upload 组件。我们设置了 Upload 组件的 name、listType、className、showUploadList、action、beforeUpload 和 onChange 属性。其中: - name 表示上传文件的参数名; - listType 表示上传列表的样式,这里设置为 picture-card; - className 表示 Upload 组件的类名; - showUploadList 表示是否显示上传列表; - action 表示上传的 URL; - beforeUpload 是一个函数,用于上传前的校验; - onChange 是一个函数,用于上传后的处理。 在 handleChange 函数中,我们根据上传文件的状态来处理上传结果,并将图片的 base64 编码保存到 state 中。最后,我们将图片显示出来,如果没有上传图片,则显示上传按钮。 在 beforeUpload 函数中,我们可以进行上传前的校验。例如,限制上传图片的大小和类型: ```jsx function beforeUpload(file) { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJpgOrPng) { message.error('You can only upload JPG/PNG file!'); } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { message.error('Image must smaller than 2MB!'); } return isJpgOrPng && isLt2M; } ``` 这个例子中,我们限制上传图片的类型为 JPG 和 PNG,大小不超过 2MB。 最后,需要引入 message、LoadingOutlined 和 PlusOutlined 组件: ```jsx import { Upload, message } from 'antd'; import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'; ``` 这样,就可以使用 Ant Design 的 Upload 组件实现图片上传功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值