Element-UI上传时修改上传图片的宽高

9 篇文章 0 订阅
// 上传前
beforeUpload(file) {
  // 创建一个Image对象
  const image = new Image();
  // 设置图片的src为选中文件的对象url
  image.src = URL.createObjectURL(file);
  return new Promise((resolve, reject) => {
    image.onload = () => {
      // 设置想要的图片宽度和高度
      const width = 100;
      const height = 200;
      // 创建一个Canvas对象
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      // 设置Canvas的宽高
      canvas.width = width;
      canvas.height = height;
      // 绘制图片
      ctx.drawImage(image, 0, 0, width, height);
      // 将Canvas转换为blob数据
      canvas.toBlob(blob => {
        if (blob) {
          // 使用新的blob对象替换原有的文件对象
          file = new File([blob], file.name, {
            type: 'image/png',
          });
          // 继续上传流程
          resolve(file);
        } else {
          reject(new Error('Canvas conversion error'));
        }
      }, 'image/png');
    };
    image.onerror = reject;
  });
},

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以给你提供一个简单的代码示例,你可以根据自己的需求进行修改。 首先,你需要在你的Vue项目中安装Element-UI: ``` npm install element-ui ``` 然后,在你的Vue组件中引入Element-UI和CSS文件: ``` <template> <div> <el-upload class="upload-demo" action="//jsonplaceholder.typicode.com/posts/" :on-preview="handlePreview" :on-remove="handleRemove" :before-upload="beforeUpload" :on-success="handleUploadSuccess" :file-list="fileList" :auto-upload="false"> <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">jpg/png文件,不超过2MB</div> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt=""> </el-dialog> </div> </template> <script> import { ElUpload, ElButton, ElDialog } from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' export default { components: { ElUpload, ElButton, ElDialog }, data() { return { dialogImageUrl: '', dialogVisible: false, fileList: [ { name: 'food.jpeg', url: 'https://www.baidu.com/img/flexible/logo/pc/result.png' } ] } }, methods: { handleRemove(file, fileList) { console.log(file, fileList) }, handlePreview(file) { this.dialogImageUrl = file.url this.dialogVisible = true }, beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' const isLt2M = file.size / 1024 / 1024 < 2 if (!isJPG) { this.$message.error('上传图片只能是 JPG/PNG 格式!') } if (!isLt2M) { this.$message.error('上传图片大小不能超过 2MB!') } return isJPG && isLt2M }, handleUploadSuccess(response, file, fileList) { console.log(response, file, fileList) } } } </script> <style scoped> .upload-demo { display: inline-block; margin-bottom: 20px; } </style> ``` 在上面的代码中,我们使用了Element-UI中的ElUpload组件来上传图片,使用ElDialog组件来显示预览图。你可以根据需要修改上传的文件类型、大小等限制条件,以及自定义上传接口和成功回调函数。 希望这个代码示例能对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值