uploader.taro.tsx 15.8 KB
Newer Older
X
xiaoyatong 已提交
1 2 3 4 5 6 7 8
import React, {
  useState,
  useImperativeHandle,
  ForwardRefRenderFunction,
  PropsWithChildren,
  useEffect,
} from 'react'
import classNames from 'classnames'
L
liuyijun17 已提交
9 10 11
import Icon from '@/packages/icon/index.taro'
import Button from '@/packages/button/index.taro'
import Taro from '@tarojs/taro'
X
xiaoyatong 已提交
12 13
import { Upload, UploadOptions } from './upload'
import bem from '@/utils/bem'
O
oasis-cloud 已提交
14
import { useConfig } from '@/packages/configprovider/configprovider.taro'
X
xiaoyatong 已提交
15 16 17 18 19 20 21 22 23 24

export type FileType<T> = { [key: string]: T }

export type FileItemStatus =
  | 'ready'
  | 'uploading'
  | 'success'
  | 'error'
  | 'removed'

L
liuyijun17 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
/** 图片的尺寸 */
interface sizeType {
  /** 原图 */
  original: string
  /** compressed */
  compressed: string
}

/** 图片的来源 */
interface sourceType {
  /** 从相册选图 */
  album: string
  /** 使用相机 */
  camera: string
  /** 使用前置摄像头(仅H5纯浏览器使用) */
  user: string
  /** 使用后置摄像头(仅H5纯浏览器) */
  environment: string
}

45 46 47
import { IComponent, ComponentDefaults } from '@/utils/typings'

export interface UploaderProps extends IComponent {
X
xiaoyatong 已提交
48 49
  url: string
  maximum: string | number
L
liuyijun17 已提交
50 51
  sizeType: (keyof sizeType)[]
  sourceType: (keyof sourceType)[]
X
xiaoyatong 已提交
52
  maximize: number
53
  defaultFileList: FileType<string>[]
X
xiaoyatong 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
  listType: string
  uploadIcon: string
  uploadIconSize: string | number
  name: string
  accept: string
  disabled: boolean
  autoUpload: boolean
  multiple: boolean
  timeout: number
  data: object
  method: string
  xhrState: number | string
  headers: object
  withCredentials: boolean
  isPreview: boolean
  isDeletable: boolean
  capture: boolean
  className: string
  defaultImg: string
  style: React.CSSProperties
  start?: (option: UploadOptions) => void
75
  removeImage?: (file: FileItem, fileList: FileType<string>[]) => void
X
xiaoyatong 已提交
76 77 78 79 80 81 82 83 84 85 86 87
  success?: (param: {
    responseText: XMLHttpRequest['responseText']
    option: UploadOptions
  }) => void
  progress?: (param: {
    e: ProgressEvent<XMLHttpRequestEventTarget>
    option: UploadOptions
  }) => void
  failure?: (param: {
    responseText: XMLHttpRequest['responseText']
    option: UploadOptions
  }) => void
88
  update?: (fileList: FileType<string>[]) => void
L
liuyijun17 已提交
89
  oversize?: (file: Taro.chooseImage.ImageFile[]) => void
90
  change?: (param: { fileList: FileType<string>[] }) => void
L
liuyijun17 已提交
91 92 93 94
  beforeUpload?: (file: any[]) => Promise<any[]>
  beforeXhrUpload?: (
    file: Taro.chooseImage.ImageFile[]
  ) => Promise<Taro.chooseImage.ImageFile[]>
95
  beforeDelete?: (file: FileItem, files: FileType<string>[]) => boolean
X
xiaoyatong 已提交
96 97 98 99
  fileItemClick?: (file: FileItem) => void
}

const defaultProps = {
100
  ...ComponentDefaults,
X
xiaoyatong 已提交
101
  url: '',
L
liuyijun17 已提交
102 103 104
  maximum: 9,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
X
xiaoyatong 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  uploadIcon: 'photograph',
  uploadIconSize: '',
  listType: 'picture',
  name: 'file',
  accept: '*',
  disabled: false,
  autoUpload: true,
  multiple: false,
  maximize: Number.MAX_VALUE,
  data: {},
  headers: {},
  method: 'post',
  defaultImg: '',
  xhrState: 200,
  timeout: 1000 * 30,
  withCredentials: false,
  isPreview: true,
  isDeletable: true,
  capture: false,
124
  beforeDelete: (file: FileItem, files: FileType<string>[]) => {
X
xiaoyatong 已提交
125 126 127 128 129 130 131
    return true
  },
} as UploaderProps

export class FileItem {
  status: FileItemStatus = 'ready'

132
  message: string = '准备中..'
X
xiaoyatong 已提交
133 134 135 136 137 138 139 140 141

  uid: string = new Date().getTime().toString()

  name?: string

  url?: string

  type?: string

L
liuyijun17 已提交
142 143 144
  path?: string

  formData: any = {}
X
xiaoyatong 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
}
const InternalUploader: ForwardRefRenderFunction<
  unknown,
  PropsWithChildren<Partial<UploaderProps>>
> = (props, ref) => {
  const { locale } = useConfig()
  const {
    children,
    uploadIcon,
    uploadIconSize,
    name,
    accept,
    defaultFileList,
    listType,
    disabled,
    multiple,
    url,
    defaultImg,
    headers,
    timeout,
    method,
    xhrState,
    withCredentials,
    data,
    isPreview,
    isDeletable,
    maximum,
    capture,
    maximize,
    className,
    autoUpload,
L
liuyijun17 已提交
176 177
    sizeType,
    sourceType,
X
xiaoyatong 已提交
178 179 180 181 182 183 184 185 186 187
    start,
    removeImage,
    change,
    fileItemClick,
    progress,
    success,
    update,
    failure,
    oversize,
    beforeUpload,
L
liuyijun17 已提交
188
    beforeXhrUpload,
X
xiaoyatong 已提交
189 190 191
    beforeDelete,
    ...restProps
  } = { ...defaultProps, ...props }
192
  const [fileList, setFileList] = useState<FileType<string>[]>([])
X
xiaoyatong 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206
  const [uploadQueue, setUploadQueue] = useState<Promise<Upload>[]>([])

  useEffect(() => {
    if (defaultFileList) {
      setFileList(defaultFileList)
    }
  }, [defaultFileList])

  const b = bem('uploader')
  const classes = classNames(className, b(''))

  useImperativeHandle(ref, () => ({
    submit: () => {
      Promise.all(uploadQueue).then((res) => {
L
liuyijun17 已提交
207
        res.forEach((i) => i.uploadTaro(Taro.uploadFile, Taro.getEnv()))
X
xiaoyatong 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220
      })
    },
  }))

  const clearUploadQueue = (index = -1) => {
    if (index > -1) {
      uploadQueue.splice(index, 1)
      setUploadQueue(uploadQueue)
    } else {
      setUploadQueue([])
    }
  }

L
liuyijun17 已提交
221 222 223 224 225 226 227 228 229 230 231 232
  const chooseImage = () => {
    if (disabled) {
      return
    }
    Taro.chooseImage({
      // 选择数量
      count: (maximum as number) * 1 - fileList.length,
      // 可以指定是原图还是压缩图,默认二者都有
      sizeType: sizeType,
      sourceType: sourceType,
      success: onChange,
    })
X
xiaoyatong 已提交
233 234 235
  }

  const executeUpload = (fileItem: FileItem, index: number) => {
L
liuyijun17 已提交
236 237
    console.log('executeUpload fileItem', fileItem, index)

X
xiaoyatong 已提交
238
    const uploadOption = new UploadOptions()
L
liuyijun17 已提交
239
    uploadOption.name = name
X
xiaoyatong 已提交
240
    uploadOption.url = url
L
liuyijun17 已提交
241
    uploadOption.fileType = fileItem.type
X
xiaoyatong 已提交
242 243 244 245 246
    uploadOption.formData = fileItem.formData
    uploadOption.timeout = timeout * 1
    uploadOption.method = method
    uploadOption.xhrState = xhrState
    uploadOption.headers = headers
L
liuyijun17 已提交
247 248 249 250 251
    uploadOption.taroFilePath = fileItem.path
    uploadOption.beforeXhrUpload = beforeXhrUpload

    console.log('uploadOption', uploadOption)

X
xiaoyatong 已提交
252 253
    uploadOption.onStart = (option: UploadOptions) => {
      clearUploadQueue(index)
254
      setFileList((fileList: FileType<string>[]) => {
X
xiaoyatong 已提交
255 256 257 258 259 260 261 262 263 264
        fileList.map((item) => {
          if (item.uid === fileItem.uid) {
            item.status = 'ready'
            item.message = locale.uploader.readyUpload
          }
        })
        return [...fileList]
      })
      start && start(option)
    }
L
liuyijun17 已提交
265

X
xiaoyatong 已提交
266 267 268 269
    uploadOption.onProgress = (
      e: ProgressEvent<XMLHttpRequestEventTarget>,
      option: UploadOptions
    ) => {
270
      setFileList((fileList: FileType<string>[]) => {
X
xiaoyatong 已提交
271 272 273 274 275 276 277 278 279 280
        fileList.map((item) => {
          if (item.uid === fileItem.uid) {
            item.status = 'uploading'
            item.message = locale.uploader.uploading
          }
        })
        return [...fileList]
      })
      progress && progress({ e, option })
    }
L
liuyijun17 已提交
281

X
xiaoyatong 已提交
282 283 284 285
    uploadOption.onSuccess = (
      responseText: XMLHttpRequest['responseText'],
      option: UploadOptions
    ) => {
286
      setFileList((fileList: FileType<string>[]) => {
X
xiaoyatong 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        update && update(fileList)
        fileList.map((item) => {
          if (item.uid === fileItem.uid) {
            item.status = 'success'
            item.message = locale.uploader.success
          }
        })
        return [...fileList]
      })
      success &&
        success({
          responseText,
          option,
        })
    }
L
liuyijun17 已提交
302

X
xiaoyatong 已提交
303 304 305 306
    uploadOption.onFailure = (
      responseText: XMLHttpRequest['responseText'],
      option: UploadOptions
    ) => {
307
      setFileList((fileList: FileType<string>[]) => {
X
xiaoyatong 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321
        fileList.map((item) => {
          if (item.uid === fileItem.uid) {
            item.status = 'error'
            item.message = locale.uploader.error
          }
        })
        return [...fileList]
      })
      failure &&
        failure({
          responseText,
          option,
        })
    }
L
liuyijun17 已提交
322

X
xiaoyatong 已提交
323 324
    const task = new Upload(uploadOption)
    if (props.autoUpload) {
L
liuyijun17 已提交
325
      task.uploadTaro(Taro.uploadFile, Taro.getEnv())
X
xiaoyatong 已提交
326 327 328 329 330 331 332 333 334 335
    } else {
      uploadQueue.push(
        new Promise((resolve, reject) => {
          resolve(task)
        })
      )
      setUploadQueue(uploadQueue)
    }
  }

L
liuyijun17 已提交
336 337 338 339
  const readFile = (files: Taro.chooseImage.ImageFile[]) => {
    const imgReg = /\.(png|jpeg|jpg|webp|gif)$/i
    files.forEach((file: Taro.chooseImage.ImageFile, index: number) => {
      let fileType = file.type
X
xiaoyatong 已提交
340
      const fileItem = new FileItem()
L
liuyijun17 已提交
341 342 343 344 345
      if (!fileType && imgReg.test(file.path)) {
        fileType = 'image'
      }
      fileItem.path = file.path
      fileItem.name = file.path
X
xiaoyatong 已提交
346 347
      fileItem.status = 'ready'
      fileItem.message = locale.uploader.readyUpload
L
liuyijun17 已提交
348
      fileItem.type = fileType
X
xiaoyatong 已提交
349

L
liuyijun17 已提交
350 351 352 353
      if (Taro.getEnv() == 'WEB') {
        const formData = new FormData()
        for (const [key, value] of Object.entries(data)) {
          formData.append(key, value)
X
xiaoyatong 已提交
354
        }
L
liuyijun17 已提交
355 356 357 358
        formData.append(name, file.originalFileObj as Blob)
        fileItem.name = file.originalFileObj?.name
        fileItem.type = file.originalFileObj?.type
        fileItem.formData = formData
X
xiaoyatong 已提交
359
      } else {
L
liuyijun17 已提交
360 361 362 363
        fileItem.formData = data as any
      }
      if (isPreview) {
        fileItem.url = file.path
X
xiaoyatong 已提交
364
      }
L
liuyijun17 已提交
365

366
      fileList.push(fileItem as any)
L
liuyijun17 已提交
367 368
      setFileList([...fileList])
      executeUpload(fileItem, index)
X
xiaoyatong 已提交
369 370 371
    })
  }

L
liuyijun17 已提交
372
  const filterFiles = (files: Taro.chooseImage.ImageFile[]) => {
X
xiaoyatong 已提交
373
    const maximum = (props.maximum as number) * 1
L
liuyijun17 已提交
374 375 376
    const maximize = (props.maximize as number) * 1
    const oversizes = new Array<Taro.chooseImage.ImageFile>()
    const filterFile = files.filter((file: Taro.chooseImage.ImageFile) => {
X
xiaoyatong 已提交
377 378 379 380 381 382 383 384 385 386
      if (file.size > maximize) {
        oversizes.push(file)
        return false
      }
      return true
    })
    if (oversizes.length) {
      oversize && oversize(files)
    }

L
liuyijun17 已提交
387 388 389
    let currentFileLength = filterFile.length + fileList.length
    if (currentFileLength > maximum) {
      filterFile.splice(filterFile.length - (currentFileLength - maximum))
X
xiaoyatong 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    }
    return filterFile
  }

  const onDelete = (file: FileItem, index: number) => {
    clearUploadQueue(index)
    if (beforeDelete && beforeDelete(file, fileList)) {
      fileList.splice(index, 1)
      removeImage && removeImage(file, fileList)
      setFileList([...fileList])
    } else {
      console.log(locale.uploader.deleteWord)
    }
  }

L
liuyijun17 已提交
405 406 407
  const onChange = (res: Taro.chooseImage.SuccessCallbackResult) => {
    // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
    const { tempFiles } = res
X
xiaoyatong 已提交
408
    if (beforeUpload) {
L
liuyijun17 已提交
409 410 411 412
      beforeUpload(tempFiles).then((f: Array<Taro.chooseImage.ImageFile>) => {
        const _files: Taro.chooseImage.ImageFile[] = filterFiles(f)
        readFile(_files)
      })
X
xiaoyatong 已提交
413
    } else {
L
liuyijun17 已提交
414
      const _files: Taro.chooseImage.ImageFile[] = filterFiles(tempFiles)
X
xiaoyatong 已提交
415 416 417
      readFile(_files)
    }

L
liuyijun17 已提交
418
    props.change && props.change({ fileList })
X
xiaoyatong 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431
  }

  const handleItemClick = (file: FileItem) => {
    fileItemClick && fileItemClick(file)
  }

  return (
    <div className={classes} {...restProps}>
      {children && (
        <div className="nut-uploader__slot">
          <>
            {children}
            {maximum > fileList.length && (
L
liuyijun17 已提交
432
              <Button className="nut-uploader__input" onClick={chooseImage} />
X
xiaoyatong 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
            )}
          </>
        </div>
      )}

      {fileList.length !== 0 &&
        fileList.map((item: any, index: number) => {
          return (
            <div className={`nut-uploader__preview ${listType}`} key={item.uid}>
              {listType == 'picture' && !children && (
                <div className="nut-uploader__preview-img">
                  {item.status === 'ready' ? (
                    <div className="nut-uploader__preview__progress">
                      <div className="nut-uploader__preview__progress__msg">
                        {item.message}
                      </div>
                    </div>
                  ) : (
                    item.status !== 'success' && (
                      <div className="nut-uploader__preview__progress">
                        <Icon
454 455
                          classPrefix={props.iconClassPrefix}
                          fontClassName={props.iconFontClassName}
X
xiaoyatong 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469
                          color="#fff"
                          name={`${
                            item.status == 'error' ? 'failure' : 'loading'
                          }`}
                        />
                        <div className="nut-uploader__preview__progress__msg">
                          {item.message}
                        </div>
                      </div>
                    )
                  )}

                  {isDeletable && (
                    <Icon
470 471
                      classPrefix={props.iconClassPrefix}
                      fontClassName={props.iconFontClassName}
X
xiaoyatong 已提交
472 473 474
                      color="rgba(0,0,0,0.6)"
                      className="close"
                      name="failure"
L
liuyijun17 已提交
475
                      onClick={() => onDelete(item, index)}
X
xiaoyatong 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
                    />
                  )}

                  {item.type.includes('image') ? (
                    <>
                      {item.url && (
                        <img
                          className="nut-uploader__preview-img__c"
                          src={item.url}
                          onClick={() => handleItemClick(item)}
                        />
                      )}
                    </>
                  ) : (
                    <>
                      {defaultImg ? (
                        <img
                          className="nut-uploader__preview-img__c"
                          src={defaultImg}
                          onClick={() => handleItemClick(item)}
                        />
                      ) : (
                        <div className="nut-uploader__preview-img__file">
                          <div
                            onClick={() => handleItemClick(item)}
                            className="nut-uploader__preview-img__file__name"
                          >
503 504 505 506 507 508
                            <Icon
                              classPrefix={props.iconClassPrefix}
                              fontClassName={props.iconFontClassName}
                              color="#808080"
                              name="link"
                            />
X
xiaoyatong 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
                            &nbsp;
                            {item.name}
                          </div>
                        </div>
                      )}
                    </>
                  )}
                  <div className="tips">{item.name}</div>
                </div>
              )}

              {listType === 'list' && (
                <div className="nut-uploader__preview-list">
                  <div
                    className={`nut-uploader__preview-img__file__name ${item.status}`}
                    onClick={() => handleItemClick(item)}
                  >
526 527 528 529 530
                    <Icon
                      classPrefix={props.iconClassPrefix}
                      fontClassName={props.iconFontClassName}
                      name="link"
                    />
X
xiaoyatong 已提交
531 532 533
                    &nbsp;{item.name}
                  </div>
                  <Icon
534 535
                    classPrefix={props.iconClassPrefix}
                    fontClassName={props.iconFontClassName}
X
xiaoyatong 已提交
536 537 538
                    color="#808080"
                    className="nut-uploader__preview-img__file__del"
                    name="del"
L
liuyijun17 已提交
539
                    onClick={() => onDelete(item, index)}
X
xiaoyatong 已提交
540 541 542 543 544 545 546 547 548 549
                  />
                  {/* 缺少进度条组件,待更新 */}
                </div>
              )}
            </div>
          )
        })}

      {maximum > fileList.length && listType === 'picture' && !children && (
        <div className={`nut-uploader__upload ${listType}`}>
550 551 552 553 554 555 556
          <Icon
            classPrefix={props.iconClassPrefix}
            fontClassName={props.iconFontClassName}
            size={uploadIconSize}
            color="#808080"
            name={uploadIcon}
          />
L
liuyijun17 已提交
557
          <Button className="nut-uploader__input" onClick={chooseImage} />
X
xiaoyatong 已提交
558 559 560 561 562 563 564 565 566 567
        </div>
      )}
    </div>
  )
}

export const Uploader = React.forwardRef(InternalUploader)

Uploader.defaultProps = defaultProps
Uploader.displayName = 'NutUploader'