vue图片转换为base64文档流

司徒隐水
2023-12-01

html代码

 <el-upload 
    v-model:file-list="detailForm.fileList" 
    action="#" 
    list-type="picture-card" 
    @change="convertImg" 
    :limit="1" 
    :auto-upload="false" 
    :on-remove="handleRemove" 
    :on-preview="handlePictureCardPreview">
        <el-icon>
            <Plus />
        </el-icon>
     </el-upload>
     <el-dialog v-model="dialogVisible" title="图片预览">
         <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%" />
     </el-dialog>

js获取文档

convertImg(file) {
    this.common.getBase64(file.raw).then(resBase64 => {
        this.detailForm.imgBase64 = "data:" + file.raw.type + ";base64," + resBase64.split(',')[1]
    })
},

common中定义转换方法

// 图片转Base64
    getBase64(file) {
        return new Promise((resolve, reject) => {
            let reader = new FileReader
            let fileResult = ""
            reader.readAsDataURL(file)
                // 开始转
            reader.onload = function() {
                    fileResult = reader.result
                }
                // 转失败
            reader.onerror = function(error) {
                    reject(error)
                }
                // 结束,返回值
            reader.onloadend = function() {
                resolve(fileResult)
            }
        })
    },

 类似资料: