base64转file上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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 @   Action_swt  阅读(88)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示