繁体   English   中英

如何在vue.js 2上使用ajax上传图像?

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

我的组件vue是这样的:

<template>
    <div class="modal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form method="post" :action="baseUrl+'/product/editImage'" enctype="multipart/form-data">
                    ...
                    <input type="file" v-on:change="changeImage" name="image" id="image" required>
                    ...
                </form>
            </div>
        </div>
    </div>
</template>
<script>
    export default{
        ...
        methods: {
            changeImage(e) {
                data = new FormData();
                data.append('file', $('#image')[0].files[0]);
                var imgname  =  $('#image').val();
                var size  =  $('#image')[0].files[0].size;
                var ext =  imgname.substr( (imgname.lastIndexOf('.') +1) );
                if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG') {
                    if(size<=5000000) {
                        $.ajax({
                            url: window.Laravel.baseUrl+'/product/addImage',
                            type: "POST",
                            data: data,
                            enctype: 'multipart/form-data',
                            processData: false,  // tell jQuery not to process the data
                            contentType: false   // tell jQuery not to set contentType
                        }).done(function(data) {
                            if (!$.trim(data)) {   
                                alert('No response');
                            }
                            else {   
                                var files = e.target.files || e.dataTransfer.files
                                if (!files.length)
                                    return;
                                this.createImage(files[0])
                                this.imageChanged = files[0]
                                $('#image').val(data);
                            }
                        });
                        return false;
                    }
                    else {
                        alert('Sorry File size exceeding from 5 Mb');
                        $('#image').val('');
                    }
                }
                else {
                    alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
                }
            },
            createImage(file) {
                var image = new Image()
                var reader = new FileReader()
                var vm = this

                reader.onload = (e) => {
                    vm.image = e.target.result
                };
                reader.readAsDataURL(file)
            },
        } 
    }
</script>

我仍然在vue.js中使用javascript 2.因为我在使用vue.js时仍然感到困惑

当我上传图片时,会出现如下错误:

未捕获的ReferenceError:未定义数据

似乎data = new FormData(); 没有在vue.js上工作

我试过它使用JavaScript,它的工作原理

但是当我将它实现到vue.js时,它不起作用

我该如何解决这个问题?

为了更好地利用Vue,我重新编写了一些代码。 除了ajax提交之外,不再使用jQuery。

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

模板

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

例子

这个插件可能适合你: Vue.ajax
它的文件上传功能可用:

HTML

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

VueJS

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

我实际上是为自己创建的,但后来我决定在Github上发布它。 我希望你能引起你的兴趣。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM