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

问题描述 投票:2回答:1

当我这样做时,我得到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格式上传图像。我只需要上传文件?

javascript jquery vue.js vuejs2 vue-component
1个回答
0
投票
  1. 删除onSubmit属性(应该拼写为onsubmit(小写)
  2. 使用vues拥有事件modifiers v-on:submit.prevent="handelSubmit"
  3. 删除return false;函数中的handelSubmit

你说“图像”就像复数? 那么也许你想将multiple属性添加到文件输入中?

<input type="file" multiple> 

对我来说,这看起来好像你想把一个from的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有效负载更改为多部分有效负载,这是上传文件的最佳选择...您可以节省更多带宽,并且需要在服务器上做更少的事情

© www.soinside.com 2019 - 2024. All rights reserved.