vue自动压缩上传图片(自动上传)

本文介绍了一种使用 image-conversion 插件实现图片压缩并上传的方法。通过 npm 安装插件后,在页面中引入并利用 Vue 的 el-upload 组件完成图片的预览、上传及压缩功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

若为自动上传请移步:https://mp.csdn.net/mp_blog/creation/editor/122559560

1.下载插件npm i image-conversion --save
2.页面引用:import * as imageConversion from 'image-conversion
3.页面

<el-upload
  action="https://jsonplaceholder.typicode.com/posts/"
  list-type="picture-card"
  :on-preview="handlePictureCardPreview"
  :before-upload="beforeRead"
  :file-list="fileList"
  :on-remove="handleRemove">
  <i class="el-icon-plus"></i>
</el-upload>

4.js文件

beforeRead(file) {
  console.log(file)
  // 上传之前校验
  return new Promise((resolve, reject) => {
    console.log('压缩前', file) // 压缩到400KB,大于400KB的图片都会进行压缩,此值可自行定义
    imageConversion.compressAccurately(file, 400).then(res => { // console.log(res)
      res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
      console.log('压缩后', res)
      resolve(res)
    })
  })
},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值