1. 使用FileReader对象
- FileReader对象可以异步读取File对象或者是Blob对象
- FileReader是一个构造函数,返回一个FileReader对象
- FileReader对象通过readAsDataUrl方法读取File对象或者Blob对象,一旦读取完成,result属性中会包含一个data: URL格式的Base64字符串以表示所读取文件的内容
- 读取完成会触发FileReader对象的onload事件,可以从FileReader对象的result属性上获取返回的结果
- 函数封装
/**
* 通过file对象/blob对象获取base64
* @param {Object} data file对象或者blob对象
*/
const getBase64 = function (data) {
return new Promise((resolve, reject) => {
let imgRes = ''
const reader = new FileReader()
reader.readAsDataURL(data)
reader.onerror = () => reject(reader.error)
reader.onload = function (e) {
// imgRes = e.target.result
imgRes = reader.result
}
reader.onloadend = () => resolve(imgRes)
})
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file" onchange="inputChange()">
<img src="" alt="预览图片">
<script>
function inputChange (e) {
const file = document.querySelector('input[type=file]').files[0]
getBase64(file).then((res) => {
const url = res
document.querySelector('img').src = url
})
}
/**
* 通过file对象/blob对象获取base64
* @param {Object} data file对象或者blob对象
*/
const getBase64 = function (data) {
return new Promise((resolve, reject) => {
let imgRes = ''
const reader = new FileReader()
reader.readAsDataURL(data)
reader.onerror = () => reject(reader.error)
reader.onload = function (e) {
// imgRes = e.target.result
imgRes = reader.result
}
reader.onloadend = () => resolve(imgRes)
})
}
</script>
</body>
</html>
- 通过图片url获取文件流blob对象案例(blob对象)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<img src="" alt="预览图片">
<button onclick="getImgByUrl()">通过url获取图片blob</button>
<script>
function getImgByUrl() {
$.ajax({ // 可能会存在跨域问题
url: 'https://p5.qhimg.com/bdr/__85/t01409d4a62e0210249.jpg',
xhrFields: {
responseType: 'blob'
},
success: (data, status) => {
getBase64(data).then((res) => {
const url = res
document.querySelector('img').src = url
})
}
})
}
</script>
</body>
</html>
2. 使用canvas.toDataURL()
/**
* 通过url获取图片base64
* @param {String} url 图片地址
*/
const getBase64ByUrl = function (url) {
return new Promise((resolve, reject) => {
let base64Url
const img = new Image()
// 如果图片url存在跨域需要设置该属性,并且后端也要允许跨域
img.setAttribute('crossOrigin', 'Anonymous')
img.src = url
img.onload = function () {
const c = document.createElement('canvas')
c.width = img.width
c.height = img.height
const ctx = c.getContext('2d')
ctx.drawImage(img, 0, 0, c.width, c.height)
base64Url = c.toDataURL()
resolve(base64Url)
}
img.onerror = function () {
reject(base64Url)
}
})
}
asd