antdv a-form的校验方式(手把手 附送上传boundary二进制流方法)

最近换了新工作,新公司的主要开发框架使用 antd 的 ui 库进行开发,其中 <a-form> 的校验小红星就是出不来,经过探索和网上搜索发现,antdv 中的 <a-form> 校验方式和熟悉的 element ui 的校验方式有一些区别,具体体现在 antd 主要是使用 <a-form> 自带的 v-decorator 属性进行校验,而不是使用 element ui 的 <el-form-item> 标签中的 ref 进行绑定校验。

<!--@author: fuyucong(congreat)-->
<!--@description: 添加升级包抽屉-->

<template>
  <a-drawer
    :title="title"
    :width="width"
    placement="right"
    :closable="false"
    @close="close"
    destroyOnClose
    :visible="modelVisible">
    <div class="tips-container">请添加要升级至的目标版本的完整的升级包</div>
    <a-form :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol" @submit="submitForm">
      <a-form-item label="升级包名称">
        <a-input
          v-decorator="['name', { rules: [{ required: true, message: '请输入升级包名称' }] }]"
          placeholder="请输入升级包名称"/>
      </a-form-item>
      <a-form-item label="选择产品">
        <a-select
          v-decorator="['productId', { rules: [{ required: true, message: '请选择产品' }] }]"
          placeholder="请选择产品"
        >
          <a-select-option v-for="item in productList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="目标版本">
        <a-input
          v-decorator="['version', { rules: [{ required: true, message: '请输入目标版本' }] }]"
        />
      </a-form-item>
      <a-form-item label="验证状态">
        <a-radio-group
          v-decorator="['verify_state', { rules: [{ required: true, message: '请选择验证状态' }] }]"
        >
          <a-radio :value="1">需要验证</a-radio>
          <a-radio :value="0">不需验证</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="上传升级包">
        <a-upload
          v-decorator="['file', { rules: [{ required: true, message: '请上传升级包' }] }]"
          name="file"
          :multiple="true"
          :showUploadList="false"
          accept=".rar,.zip,.bin"
          :customRequest="fileUpload"
          :beforeUpload="beforeUpload"
        >
          <a-button>
            <a-icon type="upload"/>
            选择文件
          </a-button>
        </a-upload>
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-button @click="close" style="margin-bottom: 0;">关闭</a-button>
      <a-button v-if="!disableSubmit"  @click="submitForm" type="primary" style="margin-bottom: 0;">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
import productService from '@api/biz/product'
import deviceOtaService from '@api/biz/deviceOta'

export default {
  name: 'addFirmware',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    disableSubmit: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      title: '添加升级包',
      width: 650,
      labelCol: {
        span: 4,
        offset: 2
      },
      wrapperCol: {
        span: 17
      },
      productList: [],
      param: {
        module: 'default',
        version: 'v'
      },
      form: this.$form.createForm(this),
    }
  },
  created() {
  },
  mounted() {
    this.getProductList()
  },
  computed: {
    modelVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  methods: {
    close() {
      this.$emit('close');
    },
    handleOk(values) {
      // this.$emit('close');
      let params = new FormData();
      // params.name = new FormData().append('name', this.param.name)
      // params.productId = new FormData().append('productId', this.param.productId)
      // params.version = new FormData().append('version', this.param.version)
      // params.module = new FormData().append('module', this.param.module)
      params.append('name', values.name)
      params.append('product_id', values.productId)
      params.append('version', values.version)
      params.append('module', 'default')
      params.append('file', this.param.file)
      params.append('verify_state', values.verify_state)
      console.log(params, 'params')
      deviceOtaService.addFirmwares(params).then(res => {
        if (res.code === 0) {
          this.$message.success('添加成功');
          this.$emit('close');
        }
      })
    },
    getProductList() {
      productService.getProductList({
        page_index: 1,
        page_size: 1000
      }).then(res => {
        if (res.code === 0) {
          this.productList = res.data.data
        }
      })
    },
    async fileUpload(info) {
      this.param.file = info.file;
    },
    beforeUpload(file) {
      const isRar = file.type === '';
      const isBin = file.type === 'application/octet-stream';
      const isZip = file.type === 'application/x-zip-compressed';
      let isType = isRar || isBin || isZip;
      if (!isType) {
        this.$message.error('只能上传rar、bin、zip格式的文件!');
      }
      const isLt30M = file.size / 1024 / 1024 < 30;
      if (!isLt30M) {
        this.$message.error('文件大小不能超过30MB!');
      }
      return isType && isLt30M;
    },
    upload(file){
      return new Promise(resolve=>{
        let reader = new FileReader()
        reader.readAsBinaryString(file);//读取文件的原始二进制数据
        reader.onload = ev=>{
          resolve(ev.target.result)
        }
      })
    },
    submitForm() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.handleOk(values)
        }
      })
    }
  }
}
</script>

        校验的重点在于在 <a-form> 标签中的 :form="form" 绑定值

<template>
    <a-form
        :form="form"
        @submit="submitForm"
    >
        <!-- 不要绑定 ref!不要绑定 v-model! -->
        <a-form-item label="目标版本>
            <a-input
                v-decorator="['version', { rules: [{ required: true, message: '请输入目标版本' }] }]"
            />
        </a-form-item>
    </a-form>
</template>

<script>
    export default {
        data() {
            return {
                form: this.$form.createForm(this) // 在此使用createForm方法绑定this,会自动创建this.form
            }
        },
        methods: {
            submitForm() {
                this.form.validateFields((err, values) => {
                    if (!err) { // 校验通过
                        console.log(values) // form中的值会通过values返回
                    }
                }
            }
        }
    }
</script>



切记:如果使用此种方法校验,不要在 <a-form-item> 上绑定 ref ,也不要在 <a-form-item> 中的元素(如 <a-input> 、<a-select> 等)中绑定 v-model ,否则会报错!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在Java中实现文件上传的常用方式是使用HTTP协议的`multipart/form-data`格式,具体实现步骤如下: 1. 创建一个`HttpURLConnection`连接对象,设置请求方法为POST,并设置连接超时时间和读取超时时间。 2. 设置请求头信息,包括`Content-Type`、`User-Agent`、`Accept-Language`等,其中`Content-Type`设置为`multipart/form-data`。 3. 创建输出,并将需要上传的文件写入到输出中。在写入文件之前需要设置一个分隔符,用于分隔不同字段的内容。 4. 在输出的末尾写入分隔符,表示文件上传结束。 5. 发送HTTP请求,并读取服务器返回的响应结果。 下面是一个Java实现文件上传的示例代码: ```java public static void uploadFile(String url, File file) throws IOException { String boundary = "---------------------------" + System.currentTimeMillis(); //设置分隔符 HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); //创建连接对象 conn.setRequestMethod("POST"); //设置请求方法为POST conn.setConnectTimeout(5000); //设置连接超时时间 conn.setReadTimeout(30000); //设置读取超时时间 conn.setDoOutput(true); //允许输出 conn.setDoInput(true); //允许输入 conn.setUseCaches(false); //不使用缓存 conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); //设置请求头信息 conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"); conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8"); OutputStream out = new DataOutputStream(conn.getOutputStream()); //创建输出 FileInputStream fileInputStream = new FileInputStream(file); //创建文件输入 byte[] buffer = new byte[1024]; int len = 0; out.write(("--" + boundary + "\r\n").getBytes()); //写入分隔符 out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n").getBytes()); out.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes()); while ((len = fileInputStream.read(buffer)) != -1) { out.write(buffer, 0, len); //写入文件数据 } out.write(("\r\n--" + boundary + "--\r\n").getBytes()); //写入分隔符 out.flush(); //清空缓存 fileInputStream.close(); //关闭文件输入 out.close(); //关闭输出 int responseCode = conn.getResponseCode(); //获取响应码 if (responseCode == 200) { InputStream inputStream = conn.getInputStream(); //获取响应输入 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //创建读取响应结果的缓冲 String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); //输出响应结果 } bufferedReader.close(); //关闭缓冲 inputStream.close(); //关闭输入 } else { System.out.println("文件上传失败,响应码为:" + responseCode); } } ``` 其中,`url`为上传文件的URL,`file`为需要上传的文件。在实际使用时,需要根据实际情况更改请求头信息、分隔符和文件字段名等参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值