如何在没有base64格式的情况下上传vue js中的图像?

时间:2017-12-20 15:46:20

标签: javascript jquery vue.js vuejs2 vue-component

当我这样做时,我得到base64编码的图像。我需要上传文件。如何更改代码

<script>
submitBox = new Vue({
  el: "#submitBox",
  data: {
  username: '',
  category: '',
  subcategory: [],
  image: '',



  },
  methods: {
    onFileChange(e) {
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length)
        return;
      this.createImage(files[0]);
    },
    createImage(file) {
      var image = new Image();
      var reader = new FileReader();
      var vm = this;

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

    handelSubmit: function(e) {
      var vm = this;
      data = {};
       data['username'] = this.username;
       data['category'] = this.category;
       data['subcategory'] = this.subcategory;
       data['image'] = this.image;
      $.ajax({
        url: 'http://127.0.0.1:8000/api/add/post/',
        data: data,
        type: "POST",
        dataType: 'json',
        success: function(e) {
          if (e.status) {
            alert("Registration Success")

            window.location.href = "https://localhost/n2s/registersuccess.html";
          } else {
            vm.response = e;

            alert("Registration Failed")
          }
        }
      });
      return false;
    }
  },
});
</script>

我的HTML代码是

<div id="submitBox">
  <form method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);">
    <input name="username" type="text" class="form-control" id="name" placeholder="Name" required="required" v-model="username" data-parsley-minlength="4"/>
    <select title="Select" v-model="category" name="category" ref="category">
      <option v-for="post in articles" v-bind:value="post.name" >{{post.name}}</option>
    </select>
    <input class="form-control" type="file" id="property-images" @change="onFileChange">
  </form>
</div>

如何在没有base64编码的情况下上传图片?当我这样做时,我只能以base64格式上传图像。我只需要上传文件吗?

1 个答案:

答案 0 :(得分:0)

  1. 删除onSubmit属性(应该拼写为onsubmit(小写)
  2. 使用vues拥有事件modifiers v-on:submit.prevent="handelSubmit"
  3. 删除return false;功能
  4. 中的handelSubmit

    你说&#34;图像&#34;它意味着复数?
    那么也许你想将multiple属性添加到文件输入中?

    <input type="file" multiple> 
    

    对我而言,这看起来好像是想要将a的post请求转换为ajax请求。所有信息都已在表单中,因此您可以轻松使用FormData constructor并选择表单元素。您只需要将name属性设置为文件输入。

    <input type="file" name="image" multiple>
    

    但我没有看到您可能需要手动添加的子类别。

    所以这就是我要做的事情:

    handelSubmit(e) {
      var form = e.target; // Get hold of the form element from the event
      var fd = new FormData(form); // create a FormData
    
      // Add the subcategory
      fd.append('subcategory', this.subcategory.join(', '));
    
      // or do this to get more of a array like:
      // (depends upon server logic)
      // 
      // this.subcategory.forEach(function(category){
      //   fd.append('subcategory', category);
      // })
    
    
      // to inspect what the formdata contains
      // better to remove in production
      // spread operator isn't cross browser compitable
      console.log(...fd);
    
      $.ajax({
        url: 'http://127.0.0.1:8000/api/add/post/',
        data: fd, // data is a FormData instance 
        type: "POST",
        processData: false, // stop jQuery's transformation
        contentType: false, // stop jQuery's from setting wrong content-type header
        success(e) {
          if (e.status) {
            alert("Registration Success")
    
            window.location.href = "https://localhost/n2s/registersuccess.html";
          } else {
            vm.response = e;
    
            alert("Registration Failed")
          }
        }
      });
    
      // For persornal reason i don't like how
      // jQuery are unhandel to accept a FormData
      // 
      // So here are some insporation if you can use the new fetch instead
      /*
      fetch('http://127.0.0.1:8000/api/add/post/', {method: 'post', body: fd})
        .then(function(res){
          // Here you have only recived the headers
    
          console.log(res.ok) // true for 2xx responses, false otherwise
    
          return res.text() // or .json()
        })
        .then(function(text){
          // Here you have recived the hole response
          console.log(text)
        })
       */
    }
    

    我无法确定您需要createImageonFileChange功能的原因。

    你还需要注意的是,当使用jQuery的ajax和Formdata时你需要将contentType和processData都设置为false,否则jQuery会对请求做错误的事情

    这会将帖子从json有效负载更改为多部分有效负载,这是上传文件的最佳选择...您可以节省更多带宽,并且需要在服务器上做更少的工作