【问题标题】:upload image using vue js with form text fields使用带有表单文本字段的 vue js 上传图像
【发布时间】:2020-03-30 15:00:40
【问题描述】:

我开始使用 Vue Js 进行小型项目,我想在我的联系表单中添加 上传文件 选项,我使用序列化作为表单,因为我有很多输入文本字段。但它不适用于 append 功能。如何将上传文件添加到我的序列化表单

这是我的代码:

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

我的 HTML 代码的一部分:

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

如何将上传文件添加到我的表单中,如您所见,我已经使用了 append 功能但它不起作用

【问题讨论】:

  • 文件上传帖子与表单帖子不同。您需要将 axios request enctype 设置为 multipart/form-data。搜索“form post file upload multipart”即可走上正轨。
  • @TheMikeInNYC 已经在 google 上检查过了,但我不知道如何使用 serialize 将文件输入与文本输入结合起来

标签: javascript jquery html vue.js nuxt.js


【解决方案1】:

两天后这是我的解决方案:

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

【讨论】:

  • oh $axios.$post('endpoint.com', formData, { headers: { 'Content-Type': 'multipart/form-data' 好主意。
  • @TheMikeInNYC 谢谢
猜你喜欢
  • 1970-01-01
  • 2020-09-05
  • 2017-10-08
  • 2016-12-14
  • 2014-12-13
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
相关资源
最近更新 更多