el-uploader 上传一张图片,before-upload中本地回显图片

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
      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值