【问题标题】:How to send the content of v-file-input?如何发送 v-file-input 的内容?
【发布时间】:2021-09-05 08:30:29
【问题描述】:

我的组件是这样的:

<template>
  <div>
    <v-file-input accept="image/*" v-model="image"></v-file-input>
    <button @click="uploadImage">Upload</button>
  </div>
</template>

<script>
export default {
  data(){
    return {
      image: null
    }
  },
  methods: {
    async uploadImage(){
      await this.$axios.put('url', {image: this.image})
    }
  }
}
</script>

如果我单击按钮并发送请求,则请求有效负载为{image: {}}。为什么? this.image的内容如何发送?

【问题讨论】:

    标签: vue.js nuxt.js vuetify.js


    【解决方案1】:

    您可能应该使用POST 而不是PUT。但是您的代码正在运行:如果您console.log(this.image),您将看到该文件,浏览器中的 Vue 开发工具也是如此。

    我不确定如何在网络选项卡中看到它,但它已正确发送到给定的后端。我猜你只需要一个合适的后端。

    这个问题在这里可能有用:How to see form data with enctype = "multipart/form-data" in Chrome debugger

    这里有一个 MDN 页面讨论 multipart/form-data 对象,即使没有关于如何查看实际有效负载的解决方案:https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

    【讨论】:

      【解决方案2】:

      只需使用 FormData 发送文件。你可以把这段代码放到uploadImage()中:

      let form = new FormData();
      form.append(file, this.file);
      this.$axios.post('url', form)
      

      然后你可以在服务器中访问它。

      【讨论】:

        【解决方案3】:

        在这里试试我做的这个代码笔 codepen v-file-input

                addImage (file) {
                if (file) {
            const reader = new FileReader()
        
            reader.onload = (e) => {
              const imgObj = new Image()
              // console.log(e.target.result)
              imgObj.src = e.target.result
              // console.log(imgObj)
              this.imageHandler = imgObj
            }
            if (file) {
              reader.readAsDataURL(file)
            }
           } else {
            console.log('error')
          }
          }
        

        主要收获:

        const reader = new FileReader()
        
        const imgObj = new Image()
        
        imgObj.src = e.target.result
        

        然后重新签名this.imageHandler = imgObj

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-08-22
          • 1970-01-01
          • 2020-11-11
          • 1970-01-01
          • 2021-03-08
          • 2021-04-29
          • 1970-01-01
          • 2020-09-07
          相关资源
          最近更新 更多