base64转file上传

const base64ToBlob = (base64Data: string, contentType: string) => {
    const byteCharacters = atob(base64Data)
    const byteArrays = []

    for (let offset = 0; offset < byteCharacters.length; offset += 512) {
      const slice = byteCharacters.slice(offset, offset + 512)

      const byteNumbers = new Array(slice.length)
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i)
      }

      const byteArray = new Uint8Array(byteNumbers)
      byteArrays.push(byteArray as never)
    }

    return new Blob(byteArrays, { type: contentType })
  }

  const blobToFile = (blob: Blob, fileName: string) => {
    const file = new File([blob], fileName, { type: blob.type })
    return file
  }



// 获取 base64 数据
      base64Bridge({ path: img.imageUrl }, async _res => {
        const _bolb = base64ToBlob(_res.base64, 'image/jpeg')
        const _file = blobToFile(_bolb, 'image.jpg')
        // const file = await compressImage(e.target.files[0])

        const formData = new FormData()
        formData.append('file', _file, Math.floor(Math.random() * 10000) + '.jpg')
        formData.append('thumbnail', 'true')

        try {
          const res = await uploadRequest({
            upload: true,
            formData: formData
          })

          if (res.code === 200) {
            const _cacheImgList = JSON.parse(sessionStorage.getItem('imgsList') || '[]')
            const _newImgList = _cacheImgList.map((t: ImgType) =>
              _id === t.id
                ? {
                  ...t,
                  ...res.data,
                  status: false
                }
                : t
            )

            sessionStorage.setItem('imgsList', JSON.stringify(_newImgList))
            props.resetImgsList(_newImgList)
          }
        } catch (_error) {
          // 失败待出errorUI
          // props.setImgsStatus(_idx, false)
        }
      })

  

posted @ 2023-10-25 11:45  Action_swt  阅读(85)  评论(0编辑  收藏  举报