file文件转base64
<el-upload
v-model:file-list="fileList"
accept="image/jpeg,image/gif,image/png"
:before-upload="beforeUpload"
:limit="1"
:on-exceed="handleExceed"
:show-file-list="false"
>
<el-button
:disabled="uploadDisabled"
size="small"
type="success"
>
<vab-icon icon="upload-2-line" />
选择图片
</el-button>
</el-upload>
主要代码:
const beforeUpload = (file) => {
console.log('file', file)
state.form.coverFile = [file]
console.log(state.form)
let _URL = window.URL || window.webkitURL
state.coverImgUrl = _URL.createObjectURL(file)
例子:这里是还另外压缩了一下文件
const imgUpload = (file) => {
return new Promise((resolve) => {
let _URL = window.URL || window.webkitURL
console.log('_URL', _URL)
let image = new Image()
image.src = _URL.createObjectURL(file)
image.onload = () => {
// 为什么要写 onload 是因为要等他加载完之后才能获取到图片宽高
resolve({
width: image.naturalWidth,
height: image.naturalHeight,
image,
}) // 2064,4608
}
})
}
const compress = async (file) => {
var imgBox = await imgUpload(file)
var bold = await imageConversion.compressAccurately(
file,
Object.assign({
size: 20, //The compressed image size is 100kb
accuracy: 0.99, //the accuracy of image compression size,range 0.8-0.99,default 0.95;
//this means if the picture size is set to 1000Kb and the
//accuracy is 0.9, the image with the compression result
//of 900Kb-1100Kb is considered acceptable;
type: 'image/jpeg',
width: imgBox.width,
height: imgBox.height,
})
)
const beforeUpload = async (file) => {
// 压缩文件
let _URL = window.URL || window.webkitURL
const croppingFile = await compress(file)
state.params.files = [croppingFile]
// 回显图片
state.url = _URL.createObjectURL(croppingFile)
// const reader = new FileReader()
// reader.readAsDataURL(file)
// reader.onload = () => {
// const base64Str = reader.result
// state.url = base64Str
// }
return false
}