Ajax-上传图片

需求

使用ajax手动提交图片文件

实现

  • Vue项目中写的demo
  • ajax提交使用axios
  • Vuefile不能像其他input一样使用v-model双向数据绑定,因为文件选择是只读,只能用onchange监控值得变化
  • 创建一个FormData对象,通过appendform对象添加数据。准备好数据后发送ajax请求上传数据
  • 上传文件需要设置请求头'Content-Type': 'multipart/form-data'

关键代码如下

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

创作不易,若本文对你有帮助,欢迎打赏支持作者!

 分享给好友: