如何将 blob 转换为 base64?

How to convert blob to base64?

         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: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

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

不知道函数setImageServer()是做什么的,可能是因为URL.createObjectURL() returns一个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

问题是我使用的是 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)
                    }
                })