How can I upload image use ajax on the vue.js 2?

偶尔善良 提交于 2019-12-07 03:02:25

I've re-worked your code a bit to make better use of Vue. jQuery is no longer used aside from the ajax submission.

new Vue({
  el:"#app",
  data:{
    allowableTypes: ['jpg', 'jpeg', 'png', 'gif'],
    maximumSize: 5000000,
    selectedImage: null,
    image: null,
    options:{
      url: 'https://httpbin.org/post',
      type: "POST",
      processData: false, 
      contentType: false 
    }
  },
  methods: {
    validate(image) {
      if (!this.allowableTypes.includes(image.name.split(".").pop().toLowerCase())) {
        alert(`Sorry you can only upload ${this.allowableTypes.join("|").toUpperCase()} files.`)
        return false
      }

      if (image.size > this.maximumSize){
        alert("Sorry File size exceeding from 5 Mb")
        return false
      }

      return true
    },
    onImageError(err){
      console.log(err, 'do something with error')
    },
    changeImage($event) {
      this.selectedImage = $event.target.files[0]
      //validate the image
      if (!this.validate(this.selectedImage))
        return
      // create a form
      const form = new FormData();
      form.append('file', this.selectedImage);
      // submit the image
      $.ajax(Object.assign({}, this.options, {data: form}))
        .then(this.createImage)
        .catch(this.onImageError);
    },
    createImage() {
      const image = new Image()
      const reader = new FileReader()
      reader.onload = (e) => {
        this.image = e.target.result
      };
      reader.readAsDataURL(this.selectedImage)
    },
  } 
})

Template

<div id="app">
  <input type="file" v-on:change="changeImage" name="image">
  <input v-if="selectedImage" v-model="selectedImage.name" type="hidden" name="photo" />
  {{image}}
</div>

Example.

This plugin may work for you: Vue.ajax
Its file upload feature is available:

HTML

<input type="file" name="my-input" id="my-input">

VueJS

Vue.ajax.post('http://example.com', [data], {
  fileInputs: [
    document.getElementById('my-input')
  ]
});

I actually created this for myself, but then I decided to publish it in Github. I hope you will take your interest.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!