【问题标题】:How to convert blob to base64?如何将 blob 转换为 base64?
【发布时间】:2021-07-27 19:06:58
【问题描述】:
         axios
            .get(RequestURL, { responseType: 'blob', withCredentials: false })
            .then((response) => {
                let imageNode = document.getElementById('image')
                let imgUrl = window.URL.createObjectURL(response.data)
                console.log(imgUrl)
                setImageServer(imgUrl)
            })

            .catch(function (error) {
                // handle error
                console.log(error)
            })
        

HTML

<img id='image' src={ImageServer} alt='Girl in a jacket' /> //getting an actual image(its working)

所有代码都可以正常工作..但问题是将该 blob 转换为 base64

目标:- 我正在尝试将此 blob 转换为 base64,以便将其保存在本地存储中

我尝试过的:-

var image = document.getElementById('image')
                console.log(image.src)  // blob:http://localhost:3000/1c012729-b104-4fb5-a9a5-39aa782860b4
                var reader = new FileReader()
                reader.readAsDataURL(image.src)
                reader.onloadend = function () {
                    var base64data = reader.result
                    console.log(base64data)
                }
            
        

使用这个我得到了错误

TypeError:无法在“FileReader”上执行“readAsDataURL”: 参数 1 不是“Blob”类型。

是的,这是在react js中,但是很容易理解为普通js(只使用状态)

【问题讨论】:

标签: javascript reactjs blob


【解决方案1】:

不知道setImageServer()这个函数是做什么的,可能是因为URL.createObjectURL()返回了DOMString(基本上是string类型):

https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

https://developer.mozilla.org/en-US/docs/Web/API/DOMString

因此,您的 console.log 正在打印出您的 blob 对象的字符串表示形式,而不是 blob 本身。您也许可以尝试将您的DOMString 转换为base64

https://reference.codeproject.com/book/javascript/base64_encoding_and_decoding

【讨论】:

  • setImageServer() 是反应状态
  • 明白了,我现在明白了。希望这个答案能帮助您解决问题!
  • 能否请您添加如何将该 dom 字符串转换为 base64 的代码?
  • 它在上面的链接中,在“Unicode 问题”下
  • var blob = b64EncodeUnicode(image.src) 并用于reader.readAsDataURL(blob) 并得到相同的错误
【解决方案2】:

问题是我使用的是image.src,而不是像respone.data那样使用来自服务器的直接响应

这就是解决方案。

  axios
                .get(RequestURL, { responseType: 'blob', withCredentials: false })
                .then((response) => {
                    console.log(response.data)
                    let imgData = window.URL.createObjectURL(response.data)
                    setImageServer(imgData)
                    var reader = new FileReader()
    
                    reader.readAsDataURL(response.data)
                    reader.onloadend = function () {
                        var base64data = reader.result
                        console.log(base64data)
                    }
                })

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 2013-09-10
    • 2020-11-10
    • 1970-01-01
    • 2015-12-20
    • 2021-06-20
    • 1970-01-01
    • 2015-03-14
    • 2019-11-18
    相关资源
    最近更新 更多