简体   繁体   中英

upload image using vue js with form text fields

I started working on small project using Vue Js and I would like to add an upload file option in my contact form, I use serialize for the form because I have a lot of input text fields . but it doesn't work with append function. How can I add upload file to my serialized form

This is my code :

addProducts () {
  const formData = $('#add-product').serialize()
  // formData.append('image', this.selectedFile, this.selectedFile.name)
  this.$axios.$post('http://endpoint.quicknsales.com/api/Product', formData).then((response) => {
    this.validation(response)
    if (response.success) { this.refresh = true }
  })
}

A part of my HTML code :

<div class="form-group mb-2">
  <div class="row">
    <div class="col-md-6">
      <label class="mb-0"><strong>Buying Price:</strong></label>
      <input
        id="product_buying_price"
        v-model="formFields.product_buying_price"
        type="text"
        class="form-control rounded-0"
        placeholder="Product Buying Price"
        name="general[product_buying_price]"
      >
    </div>
    <div class="col-md-6">
      <label class="mb-0"><strong>Selling Price:</strong></label>
      <input
        id="product_selling_price"
        v-model="formFields.product_selling_price"
        type="text"
        class="form-control rounded-0"
        placeholder="Product Selling Price"
        name="general[product_selling_price]"
      >
      <input id="file" type="file" name="general[file]">
    </div>
  </div>
</div>

How can I add the upload file to my form, as you can see I have already used append function but it doesn't work

after two days this is my solution :

const formData = new FormData()
  formData.append('image', this.selectedFile, this.selectedFile.name)
  $($('form-in-question').serializeArray()).each(function (i, field) {
    formData.append(field.name, field.value)
  })
  this.$axios.$post('endpoint.com', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then((response) => {
    this.validation(response)
    if (response.success) { this.refresh = true }
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM