2

When I do this way I am getting base64 encoded image. I need to just upload the file. How can I change the code

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

My html code is

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

How can I able to upload images without base64 encoding? When I am doing this way I am only able to upload image in base64 format. I need just file upload?

5
  • You asked this already today. Commented Dec 20, 2017 at 15:52
  • where.. please give me a solution Commented Dec 20, 2017 at 15:53
  • I mean this stackoverflow.com/questions/47810962/… I thought it was today, but still you didn't ask the question clearly then Commented Dec 20, 2017 at 15:55
  • do you want to upload images directly? Commented Dec 20, 2017 at 16:01
  • yes sir.. i need to upload image without base64.. can you help me Commented Dec 20, 2017 at 16:03

1 Answer 1

0
  1. Remove onSubmit attribute (that should really be spelled onsubmit (lowercased)
  2. Use vues owns event modifiers v-on:submit.prevent="handelSubmit"
  3. Remove return false; in handelSubmit function

You are say "images" like it means plural?
So maybe you wanna add the multiple attribute to the file input?

<input type="file" multiple> 

To me this all really seems like you want to turn a post request of a from into a ajax request. All the information is already in the form so you could just easily use the FormData constructor and select the form element. You just need to set the name attribute to the file input as well.

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

But I don't see the subcategory which you might need to add manually.

So here is what i would have done:

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

I fail to see the reason why you would need the createImage and the onFileChange functions.

The thing you also have to notices is that when using jQuery's ajax and and Formdata is that you need to set both contentType and processData to false otherwise jQuery will do incorrect things to the request

This will change the post from a json payload to a multipart payload which is the best choice for uploading files... you save more bandwidth and need to do less on the server

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.