【Vue3】 typescript element-plus使用el-upload组件实现,上传一张图片并显示图片,根据图片url获取图片base64编码

html

<el-upload
     ref="uploadRef"
     class="avatar-uploader"
     :action="''"
     :auto-upload="false"
     :limit="1"
     :show-file-list="false"
     :on-change="handleChange"
     :on-exceed="handleExceed"
     >
     <el-button  type="primary" plain>
         <el-icon :size="20" class="m-r-2"><Files /></el-icon>
        从本地上传图片
     </el-button>
 </el-upload>
 <!--显示上传的图片-->
 <div style="width: 600px;height: 400px;position: relative;">
      <img :src="imageUrl" style="height: 400px;margin: 0 auto;">
  </div>
  <el-button :loading="tongueLoading" type="primary" size="default" @click="uploadPhoto">
     <el-icon :size="20" class="m-r-2"><Upload /></el-icon>
      上传图片
  </el-button>

javascript

// 文件变化时触发
    const handleChange = (file, fileList) => {
        console.log('File change', file, fileList);
        let { type, size } = file.raw
        if (size > 1 * 1024 * 1024) {
    
            ElMessage({
                message: '文件大小不能超过1M',
                type: 'warning'
            })
            return
        }
        let allowType = ['image/jpeg', 'image/png', 'image/jpg']
        if (!allowType.includes(type)) {
            ElMessage({
                message: '请上传格式为jpg/png/jpeg格式的图片',
                type: 'warning'
            })
            return
        }
        // 更新图片预览 URL
        imageUrl.value = URL.createObjectURL(file.raw);
        getBase64(file.raw)
        tongueStep.value = 2;


    };
    const handleExceed: UploadProps['onExceed'] = (files) => {
        uploadRef.value!.clearFiles()
        const file = files[0] as UploadRawFile
        file.uid = genFileId()
        uploadRef.value!.handleStart(file)
    }
    let getBase64 = (file) => {
        return new Promise(function (resolve, reject) {
            const reader = new FileReader()
            let imgResult: any = ''
            reader.readAsDataURL(file)
            reader.onload = function () {
                imgResult = reader.result
                base64String.value = imgResult
    
            }
            reader.onerror = function (error) {
                reject(error)
            }
            reader.onloadend = function () {
                resolve(imgResult)
            }
        })
    }
    // 发送上传
    const uploadPhoto = async (type:string) => {
        let imageStr = base64String.value.split('base64,')[1]
        const formData = new FormData();
        const data = {
            image: imageStr
        };
        tongueLoading.value = true;
        hasResult.value = false;
        fetch('接口', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin':'*'
        },
        body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            console.log(data)
            
            
        })
        .catch(error => {
           
            console.log(error)
        });
    };

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值