vue 自定义上传图片

vue自定义上传图片

1.用elementUI 里的el-upload上传

   <div class="businesster">
        <el-form-item label="封面图片" prop="headImg">
          <div class="businesster_ying">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :on-preview="handlePreview"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadFile"
            >
                <el-button class="f_picture">点击上传</el-button>
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
                style="width: 200px"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <div slot="tip" class="el-upload__tip">
          <p>
            推荐尺寸750*272;支持.jpg, .jpeg, .bmp, .gif,
            .png类型文件,5M以内
          </p>
        </div>
      </div>

2.:http-request="uploadFile"用自定义上传

js

    data() {
    return {
    	 base64img:"",
    	 imageUrl: require("../../assets/images/andy.png"),
    	 //默认给一张图片
    		}
    }
		  methods: {
	    uploadFile(params){
	      var _this = this
	      console.log("uploadFile",params)
	       if (params.file.name) {
	        var reader = new FileReader();
	        //通过文件流将文件转换成Base64字符串
	        reader.readAsDataURL(params.file);
	        reader.onloadend = function () {
	          // 把转换过得base赋值给全局变量
	          // 这里reader.result就是转换好的bsae64格式图片
	          _this.base64img = reader.result;
	          // console.log(this.base64img);
	          //  this.imageUrl  = URL.createObjectURL(params.file)
	           _this.imageUrl  = _this.base64img,
	           console.log(_this.imageUrl)
	        };
	      }
	    }, 
	      beforeAvatarUpload(file) {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isWebp = file.type === "image/webp";
  const isGif = file.type === "image/gif";
  const isBmp = file.type === "image/bmp";
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isJPG && !isPNG && !isWebp && !isGif && !isBmp) {
    this.$message.error(
      "上传封面图片只能是 JPG、png、GIF、JPEG、BMP、webp 格式!"
    );
  }
  if (!isLt5M) {
    this.$message.error("上封面图片大小不能超过 5MB!");
  }
  return (isJPG || isPNG || isWebp || isGif || isBmp) && isLt5M;
},
	  }

3.要注意的是uploadFile 方法没起到作用 是this指向的问题

在这里插入图片描述

补充一下:elementUI里的上传图片显示问题

   //自定义上传方法
   http_request_two(params,fileList){
      console.log(params,"修改营业执照");
      // 需要用URL.createObjectURL()方法转一下file,页面上图片才能加载出来
        this.imageUrl = URL.createObjectURL(params.file)
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值