vue项目将file转换成二进制流

前端在新增数据时,需要将附件和表单数据一起上传,此时需要将文件转换成二进制流传给后端。记录将文件转换成二进制流

<el-form-item label="产品概况附件" :label-width="formLabelWidth">
  <el-upload
    ref="uploadProduct"
    class="upload-demo"
    :auto-upload="false"
    :limit="1"
    :on-exceed="handleExceed"
    :file-list="fileListProduct"
    :data="uploadFormProduct"
    :on-success="onSuccess"
    :on-error="onError"
    :on-change="onChangeProduct"
    :before-remove="handleRemoveProduct"
    name="enterprise_product_file"
  >
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
  </el-upload>
</el-form-item>
<script>
export default {
  data() {
    return {
      // 上传附件(产品概况)
      fileListProduct: []
    };
  },
  methods: {
    // 上传
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件,本次选择了 ${
          files.length
        } 个文件,共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    onSuccess(files, fileList) {
      this.$parent.findAllEnterprise();
      this.$message({
        message: "成功",
        type: "success"
      });
      this.handlerClose();
    },
    onError() {
      this.$message({
        message: "网络错误",
        type: "warning"
      });
    },
    handleRemoveProduct(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`).then(() => {
        // this.isUploadFileProduct = false
        this.fileListProduct.pop(file);
      });
    },
    handlePreview(file) {
      console.log(file);
    },
    onChangeProduct(file, fileList) {
      // console.log(file)
      if (/.(txt)$/.test(file.name)) {
        this.$message({
          message: "不允许上传以txt结尾的文件",
          type: "warning"
        });
        this.$refs.uploadProduct.clearFiles();
        return
      }
      // 当选择好上传文件时,将这个文件的信息push到数组中去
      this.fileListProduct.push(file);
    },
    // 新增
    addEnterprise() {
      // 将上传的文件附件转成二进制转给后台 this.form就是表单输入框的内容
      const formData = new FormData();
      Object.keys(this.form).forEach(key => {
        if (key === "enterprise_product_file") {
	  // 判断是否是产品概况的字段,是的话将刚刚push进fileListProduct转换成二进制给后台
	  // 注意,需要的是写到raw,否则传给后端就是"[object, object]"
          formData.append(key, this.fileListProduct[0].raw);
        } else {
	  // 若是表单中的字段,则直接append进去
          formData.append(key, this.form[key]);
        }
      });
      // 调用vuex中的方法,将formData传给后端。此时上传的附件已经转换成二进制流
      this.addEnterpriseCustomers(formData)
        .then(() => {
          this.$message({
            type: "success",
            message: "保存成功!"
          });
          this.$parent.findAllEnterprise();
          this.handlerClose();
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "网络异常"
          });
        });
    },
    // 修改
    updateEnterprise() {
      const formData = new FormData();
      Object.keys(this.form).forEach(key => {
        if (
          key === "enterprise_product_file" &&
          this.fileListProduct.length !== 0
        ) {
          formData.append(key, this.fileListProduct[0].raw);
        } else if (
          key === "enterprise_introduct_file" &&
          this.fileListIndoc.length !== 0
        ) {
          formData.append(key, this.fileListIndoc[0].raw);
        } else {
          formData.append(key, this.form[key]);
        }
      });
      const params = {
        id: this.form.enterprise_pk_id,
        form: formData
      };
      // delete params.form.enterprise_pk_id
      this.updateEnterpriseCustomers(params)
        .then(() => {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.handlerClose();
          this.$parent.findAllEnterprise();
        })
        .catch(() => {
          this.$message({
            message: "网络错误",
            type: "warning"
          });
        });
    }
  }
};
</script>
posted @ 2020-06-09 16:37  zhongfang99  阅读(2935)  评论(0编辑  收藏