Read the content of the uploaded file in Vue and convert it to base64 encoding, and pass it to the backend interface

Sometimes it is necessary to convert the uploaded file to base64 encoding and then pass it to the backend for use. At this time, the FileReader object is used to read the file content and convert it to base64 encoding for use.

FileReader function explanation:

//了解原理
let reader = new FileReader()
reader.readAsDataURL(f.files[0])  //把目标文件转地址,文件来自于上传组件。
....读取中
reader.onload = function () { //文件读取成功时触发
    myimg.src=reader.result // 如果用于直接展示图片,就可以这样使用
}



1.FileReader : 读取文件内容
readAsText() 读取文本文件,(可以使用Txt打开的文件)
readAsBinaryString(): 读取任意类型的文件,返回二进制字符串
readAsDataURL: 方法可以将读取到的文件编码成DataURL ,可以将资料(例如图片、excel文件)内嵌在网页之中,不用放到外部文件
abort: 中断读取
2.FileReader 提供一个完整的事件模型,用来捕获读取文件的状态
onabort:读取文件断片时触发
onerror:读取文件错误时触发
onload:文件读取成功时触发
onloadend:文件读取完毕之后,不管成功还是失败触发
onloadstart: 开始读取文件时触发
onprogress:读取文件过程中触发

But pay attention here: the result read by FileReader is not simply base64 encoding, but something with a data type prefix:

If it is a picture, it will contain: data:image/png;base64, this prefix

So if you pass it to the backend interface, you need to replace this part: event!.target.result.split("base64,")[1]

Otherwise, an error will be reported: Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range. It is not a usable base64 content

So you need to replace the above prefix. 

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/131536958