在Vue项目中写的demo
ajax提交使用axios
在Vue中file不能像其他input一样使用v-model双向数据绑定,因为文件选择是只读,只能用onchange监控值得变化
创建一个FormData对象,通过append向form对象添加数据。准备好数据后发送ajax请求上传数据
上传文件需要设置请求头’Content-Type’: ‘multipart/form-data’
作者:喵巨人
原文:http://vuepress.wmm66.com/%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/javascript/Ajax-%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87.html#%E9%9C%80%E6%B1%82
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

<input type="file" ref="file" @change="getFile" />
<button @click="uploadFile">上传</button>

getFile (e) {
  this.image = e.target.files[0]
},
uploadFile () {
  // console.log(this.$refs.file.files)
  if (this.image) {
    let param = new FormData() // 创建form对象
    param.append('image', this.image, this.image.name) // 通过append向form对象添加数据
    param.append('id', 47)
    axios.post('http://xxx/api/upImage', param, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'usertoken': 'afelagfjlaewgj55feagj3qfasf'
      }
    }).then(res => {
      console.log(res)
    })
  }
}

By lxcss

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注