如何在vue js html中添加多个图像和其他输入字段?

Wan*_*rer 24 html javascript jquery vue.js vue-component

我的HTML代码是

我还需要添加阵列格式的sez,我还需要添加多个图像,需要提供添加图像,点击它时需要根据客户需要添加图像

<form method="POST" enctype="multipart/form-data" v-on:submit.prevent="handleSubmit($event);">
  <div class="row">
    <div class="col-md-4">
      <div class="form-group label-floating">
        <label class="control-label">Name</label>
        <input type="text" class="form-control" v-model="name">
      </div>
    </div>
    <div class="col-md-4">
      <div class="form-group label-floating">
        <label class="control-label">Alias</label>
        <input type="text" class="form-control" v-model="alias">
      </div>
    </div>
    <div class="col-md-4">
      <div class="form-group label-floating">
        <label class="control-label">Sex</label>
        <select class="form-control" v-model="sex" id="level">
        <option value="Male">Male</option>
        <option value="female">Female</option>
        </select>
      </div>
    </div>
  </div>
  <div class="row" v-for="(book, index) in sez" :key="index">


    <div class="col-md-4">
      <div class="form-group label-floating">
        <label class="control-label">Date </label>
        <input type="date" class="form-control" v-model="book.date">
      </div>
    </div>
    <div class="col-md-8">
      <div class="form-group label-floating">
        <label class="control-label"> Details</label>
        <input type="text" class="form-control" book.details>
      </div>
    </div>

  </div>
  <a @click="addNewRow">Add</a>

  <div class="card-content">
    <div class="row">
      <div class="col-md-4">
        <div class="button success expand radius">
          <span id="save_image_titlebar_logo_live">Signature</span>
          <label class="custom-file-upload"><input type="file" name="photo" accept="image/*"  />
        </label>
        </div>
      </div>
      <div class="col-md-4">
        <div class="button success expand radius">
          <span id="save_image_titlebar_logo_live">Recent Photograph</span>
          <label class="custom-file-upload">
        <input type="file" name="sign"/>
        </label>
        </div>
      </div>
    </div>
  </div>
</form>
Run Code Online (Sandbox Code Playgroud)

我的vue js代码是

addForm = new Vue({
  el: "#addForm",
  data: {
    name: '',
    alias: '',
    sex: '',
    sez: [{
      date: null,
      details: null,

    }, ],
    photo: '',
    sign: '',
  },
  methods: {
    addNewRow: function() {
      this.seziure.push({
        date: null,
        details: null,
      });
    },

    handleSubmit: function(e) {
      var vm = this;
      data = {};
      data['sez'] = this.sez;
      data['name'] = this.name;
      data['alias'] = this.alias;
      data['sex'] = this.sex;
      //how to add images
      $.ajax({
        url: 'http://localhost:4000/save/',
        data: data,
        type: 'POST',
        dataType: 'json',
        success: function(e) {
          if (e.status) {
            vm.response = e;
            alert("success")

          } else {
            vm.response = e;
            console.log(vm.response);
            alert("Registration Failed")
          }
        }
      });
      return false;
    },
  },
});
Run Code Online (Sandbox Code Playgroud)

这是我的代码.在这种情况下,我不知道如何添加图像.

任何人都可以帮我传递这些数据.

如何将这些数据与图像一起传递给后端?

我不想使用base64编码.我需要在此ajax post请求中传递此图像以及其他数据

Mar*_*oni 10

使用axios:

模板

...
<input type="file" name="photo" accept="image/*" @change="setPhotoFiles($event.target.name, $event.target.files) />
...
Run Code Online (Sandbox Code Playgroud)

data () {
  return {
    ...
    photoFiles: [],
    ...
  }
},
...
methods: {
  ...
  setPhotoFiles (fieldName, fileList) {
    this.photoFiles = fileList;
  },
  ...
  handleSubmit (e) {
    const formData = new FormData();

    formData.append('name', this.name);
    formData.append('alias', this.alias);
    formData.append('sex', this.sex);
    ...
    this.photoFiles.forEach((element, index, array) => {
      formData.append('photo-' + index, element);
    });

    axios.post("http://localhost:4000/save/", formData)
      .then(function (result) {
        console.log(result);
        ...
      }, function (error) {
        console.log(error);
        ...
      });
  }
}
Run Code Online (Sandbox Code Playgroud)


Sal*_* CJ 9

我不确定您希望在哪里显示额外的图像,但我在此列之后添加了它们:

<div class="col-md-4">
  <div class="button success expand radius">
    <span id="save_image_titlebar_logo_live">Recent Photograph</span>
    <label class="custom-file-upload">
  <input type="file" name="sign"/>
  </label>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这里是我添加的专栏 - "添加图片":( 您可以在这里尝试此功能,更新)

<div class="col-md-4">
  <ul class="list-group" :if="images.length">
    <li class="list-group-item" v-for="(f, index) in images" :key="index">
      <button class="close" @click.prevent="removeImage(index, $event)">&times;</button>
      <div class="button success expand radius">
        <label class="custom-file-upload">
          <input type="file" class="images[]" accept="image/*" @change="previewImage(index, $event)">
        </label>
      </div>
      <div :class="'images[' + index + ']-preview image-preview'"></div>
    </li>
  </ul>
  <button class="btn btn-link add-image" @click.prevent="addNewImage">Add Image</button>
</div>
Run Code Online (Sandbox Code Playgroud)

和完整的Vue JS代码(带jQuery.ajax()):

addForm = new Vue({
  el: "#addForm",
  data: {
    name: '',
    alias: '',
    sex: '',
    sez: [{
      date: null,
      details: null
    }],
    // I removed `photo` and `sign` because (I think) the're not necessary.
    // Add I added `images` so that we could easily add new images via Vue.
    images: [],
    maxImages: 5,
    // Selector for the "Add Image" button. Try using (or you should use) ID
    // instead; e.g. `button#add-image`. But it has to be a `button` element.
    addImage: 'button.add-image'
  },
  methods: {
    addNewRow: function() {
      // I changed to `this.sez.push` because `this.seziure` is `undefined`.
      this.sez.push({
        date: null,
        details: null
      });
    },

    addNewImage: function(e) {
      var n = this.maxImages || -1;
      if (n && this.images.length < n) {
        this.images.push('');
      }
      this.checkImages();
    },

    removeImage: function(index) {
      this.images.splice(index, 1);
      this.checkImages();
    },

    checkImages: function() {
      var n = this.maxImages || -1;
      if (n && this.images.length >= n) {
        $(this.addImage, this.el).prop('disabled', true);  // Disables the button.
      } else {
        $(this.addImage, this.el).prop('disabled', false); // Enables the button.
      }
    },

    previewImage: function(index, e) {
      var r = new FileReader(),
        f = e.target.files[0];

      r.addEventListener('load', function() {
        $('[class~="images[' + index + ']-preview"]', this.el).html(
          '<img src="' + r.result + '" class="thumbnail img-responsive">'
        );
      }, false);

      if (f) {
        r.readAsDataURL(f);
      }
    },

    handleSubmit: function(e) {
      var vm = this;

      var data = new FormData(e.target);
      data.append('sez', this.sez);
      data.append('name', this.name);
      data.append('alias', this.alias);
      data.append('sex', this.sex);

      // The `data` already contain the Signature and Recent Photograph images.
      // Here we add the extra images as an array.

      $('[class~="images[]"]', this.el).each(function(i) {
        if (i > vm.maxImages - 1) {
          return; // Max images reached.
        }

        data.append('images[' + i + ']', this.files[0]);
      });

      $.ajax({
        url: 'http://localhost:4000/save/',
        data: data,
        type: 'POST',
        dataType: 'json',
        success: function(e) {
          if (e.status) {
            vm.response = e;
            alert("success");
          } else {
            vm.response = e;
            console.log(vm.response);
            alert("Registration Failed");
          }
        },
        cache: false,
        contentType: false,
        processData: false
      });

      return false;
    },
  },
});
Run Code Online (Sandbox Code Playgroud)

补充说明

我知道你在后端使用Node.js; 但是,我应该提到在PHP中,$_FILES变量将包含所有图像(只要字段name被正确设置); 我想Node.js有一个类似的变量或获取文件的方式.

而在下面input,你可能已经忘记了包裹book.detailsv-model:

<input type="text" class="form-control" book.details>
<input type="text" class="form-control" v-model="book.details"> <!-- Correct -->
Run Code Online (Sandbox Code Playgroud)

UPDATE

添加了限制允许选择/上传的图像数量的功能,并添加了所选图像的预览.再加上"发送图像array"修复.