vue上传图片功能实现

vue上传图片功能实现

HTML部分
          <el-form-item label="上传图片:" prop="pictureUrl" class="aa">
            <el-upload
              class="avatar-uploader uploadPics"
              action="#"
              ref="upload"
              :http-request="requestUpload"
              :show-file-list="false"
              :before-upload="beforeUpload"
            >
              <img
                v-if="imageUrl || formLabelAlign.pictureUrl"
                :src="imageUrl || formLabelAlign.pictureUrl"
                class="avatar"
              />
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
                style="width: 178px; height: 178px"
              ></i>
            </el-upload>
          </el-form-item>
js部分(前端调接口上传)
    beforeUpload(file) {
      let isJPG = /jpeg|jpg|png/.test(file.type),
        isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("图片只能是 JPG/JPEG/PNG格式!");
        return;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
        return;
      }
      let formData = new FormData();
      formData.append("file", file);
      this.$http.upload("/aim/file/upload", formData).then((res) => {
        if (res.data.code === 200) {
          var data = res.data.data;
          this.$http
            .post("/aim/file/getFileUrl", {
              url: res.data.data,
            })
            .then((res) => {
              //this.imgUrl = res.data;
              this.imgUrl = res.data;
              this.formLabelAlign.pictureUrl = this.imgUrl;
              this.imageUrl = this.imgUrl;
            });
          this.pictures = this.$store.state.imgHost + data;
        }
      });
    },
提交表单
    submitGroup(form) {
      if (this.formLabelAlign.pictureUrl == "") {
        this.$message.error("请上传图片")
        return
      }
      this.$refs["formLabelAlign"].validate((valid) => {
        if (valid) {
          this.loadingsave = true;
          if (this.pictures) {
            form.pictureUrl = this.pictures.replace(this.$store.state.imgHost, "");
          } else {
            form.pictureUrl = this.pictures;
          }
         //新增或修改接口部分
         this.$http...
}
css样式
<style scoped>
.avatar {
  width: 190px;
  height: 190px;
  display: block;
  border-radius: 10px;
}

.aa .avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border-radius: 10px;
}

.uploadPics .el-upload {
  width: 178px !important;
}

.hide .el-upload--picture-card {
  display: none;
}

.aa .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.aa .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

</style>
上一篇:js 实现点击空白关闭弹框


下一篇:多重背包