【问题标题】:How can I add multiple images along with other input fields in vue js html?如何在 vue js html 中添加多个图像以及其他输入字段?
【发布时间】:2018-10-01 03:02:22
【问题描述】:

我的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>

我的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;
    },
  },
});

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

谁能帮我传递这些数据。

如何将此数据与图像一起传递到后端?

我不想使用 base64 编码。我只需要在这个 ajax 发布请求中传递这个图像以及其他数据

【问题讨论】:

  • This question 有几个使用 Vue 上传文件的选项。此外,谷歌搜索“vue 上传文件”返回了很多可以帮助您的结果。
  • 您是否只是在寻找文件上传,我使用了 formData 但我有疑问,因为您有一个数组..否则您可以使用 formdata 我认为..如果您得到这个答案,那将是一个对我也有帮助。当您收到相同的内容时,只需上传
  • 你在后台有什么?
  • node js 先生.. 我只需要从前端传递数据
  • 这个视频可能有用youtube.com/watch?v=327haEC7iFA&t=899s

标签: javascript jquery html vue.js vue-component


【解决方案1】:

使用axios:

模板

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

代码

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);
        ...
      });
  }
}

【讨论】:

  • 先生,我将如何通过 sez?
  • @Wanderer FormData 对象可以包含多个具有相同名称的条目,因此只需初始化传递表单元素的 FormData,或多次附加 sez.data 和 sez.details。
【解决方案2】:

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

<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>

这是我添加的栏目——“添加图片”:(您可以试试这个功能here,有更新)

<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>

以及完整的 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;
    },
  },
});

附加说明

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

而在下面的input 中,你可能忘记将book.details 包裹在v-model 中:

<input type="text" class="form-control" book.details>
<input type="text" class="form-control" v-model="book.details"> <!-- Correct -->

更新

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

【讨论】:

  • 先生,非常感谢。还有一个疑问,是否可以将图像作为数组发送(就像我们对性所做的那样)而不是作为 image1、image2 发送
  • 尝试将&lt;input type="file" :name="'images' + (index + 1)" accept="image/*"&gt; 更改为&lt;input type="file" name="images[]" accept="image/*"&gt;。
  • -----WebKitFormBoundary3Qe1EHbkhF33YbFF 内容处置:表单数据;名称=“图像[]”; filename="logo123.png" Content-Type: image/png ------WebKitFormBoundary3Qe1EHbkhF33YbFF Content-Disposition: form-data;名称=“图像[]”; filename="n1opy.png" 内容类型:image/png
  • 这来了,先生
  • 先生还有为什么给你:if="images.length"
【解决方案3】:

如果您使用的是 HTML5,请尝试使用 FormData 对象;它将对您的文件输入内容进行编码:

var myForm = document.getElementById('addForm');
formData = new FormData(myForm);
data: formData

【讨论】:

  • 能否请您说明如何通过此代码添加 sez
  • FormData 对象应该使用每个元素的 name 属性包含表单的所有键/值。尝试在输入字段中添加名称。你也可以通过 FormData 发送一个数组:for (var i = 0; i &lt; sez.length; i++) { formData.append('sez[]', sez[i]); }
【解决方案4】:

使用下面的模板显示/上传图片:

 <div v-if="!image">
    <h2>Select an image</h2>
    <input type="file" @change="onImageUpload">
  </div>
  <div v-else>
    <img :src="image" />
    <button @click="removeImage">Remove image</button>
  </div>

js代码:

data: {
    image: '',
    imageBuff: ''
},
methods: {
    onImageUpload(e) {
        var files = e.target.files || e.dataTransfer.files;
        if (!files.length)
            return;
        this.createImage(files[0]);
    },
    createImage(file) {
        var image = new Image();
        var reader = new FileReader();
        this.imageBuff = file;

        reader.onload = (e) => {
            this.image = e.target.result;
        };
        reader.readAsDataURL(file);
    },
    removeImage: function(e) {
        this.image = '';
    },
    handleSubmit(e) {
        const formData = new FormData();

        formData.append('name', this.name);
        formData.append('alias', this.alias);
        formData.append('sex', this.sex);
        formData.append('image', this.imageBuff);
        ...

        // Ajax or Axios can be used
        $.ajax({
            url: 'http://localhost:4000/save/',
            data: formData,
            processData: false, // prevent jQuery from automatically transforming the data into a query string.
            contentType: false,
            type: 'POST',
            success: function(data) {
                console.log(data);
                ...
            }
        });

    }
}

【讨论】:

  • 这种情况下如何添加多张图片。在这种情况下如何添加 sez[]。请也显示出来..
猜你喜欢
  • 2018-11-01
  • 1970-01-01
  • 2020-10-13
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2021-07-11
  • 2023-01-27
  • 2021-05-21
相关资源
最近更新 更多