其他分享
首页 > 其他分享> > vue表单中如何上传图片

vue表单中如何上传图片

作者:互联网

form表单中定义上传图片的组件

<el-form-item :label="$t('lang.contentManage.sysImage')" prop="sysImage">

          <el-upload
            class="upload-demo"
            action="#"
            accept=".jpg, .png"
            :auto-upload="false"
            :on-change="uploadFile"
            :show-file-list="false"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else ></i>
            <el-button size="mini" type="primary" icon="el-icon-upload2"
              >{{$t('lang.contentManage.uploadPicture')}}
            </el-button>
          </el-upload>

          
        </el-form-item>

  

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

  data中定义一下

imageUrl: '',

  methods中

//上传文件
      uploadFile (item) {
          let file = item.raw
          this.form.file = file
          
          this.imageUrl=window.URL.createObjectURL(file)
          
      },

  提交表单

 this.$refs["form"].validate(valid => {
            if (valid) {
              if (this.form.id != undefined) {
                let formData = new FormData()
                formData.append("id",this.form.id)
                formData.append("file",this.form.file)
                formData.append("sysDesc",this.form.sysDesc)
                formData.append("sysKeys",this.form.sysKeys)
                formData.append("sysName",this.form.sysName)
                updateSys(formData).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                let formData = new FormData()
                
                formData.append("file",this.form.file)
                formData.append("sysDesc",this.form.sysDesc)
                formData.append("sysKeys",this.form.sysKeys)
                formData.append("sysName",this.form.sysName)
                updateSys(formData).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            }
          });

  后端获取表单中的数据

@ApiOperation(value="修改Site settings")
    @PutMapping("/updateFile")
    public AjaxResult updateFile(SystemFile systemFile, @RequestParam(value = "file",required = false)  MultipartFile file) throws IOException {}

  

标签:sysName,vue,form,formData,表单,file,178px,上传,append
来源: https://www.cnblogs.com/sgj191024/p/16576030.html