2017-12-20 21 views
1

이렇게하면 base64로 인코딩 된 이미지가 표시됩니다. 파일을 업로드해야합니다. 어떻게 코드를 변경할 수 있습니다base64 형식이 아닌 vue js에서 이미지를 업로드하는 방법은 무엇입니까?

<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 코드는 내가 할 수 base64 인코딩없이 이미지를 업로드 할 수있는 방법

<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 형식으로 이미지를 업로드 할 수만 있습니다. 파일 업로드 만하면됩니까?

+0

당신은 이것을 이미 요청했습니다. – samayo

+0

어디 .. 제게 해결책을주십시오 – med

+0

이 말은 https://stackoverflow.com/questions/47810962/how-can-i-able-to-upload-picture-using-vue-js입니다. 저는 그것이 오늘이라고 생각했습니다. 그래도 여전히 질문을하지 않았다면 – samayo

답변

0
  1. 제거 onSubmit 속성 (즉, 정말 onsubmit (소문자)
  2. 사용 vues 철자되어야한다

당신이 좋아 "이미지"라고 있습니다 handelSubmit 기능에 return false;을 제거 이벤트를 modifiersv-on:submit.prevent="handelSubmit"

  • 를 소유 복수형을 의미합니까?
    multiple 속성을 파일 입력에 추가 하시겠습니까?

    <input type="file" multiple> 
    

    제게 이것은 ajax 요청으로 from의 게시물 요청을 돌리고 싶은 것처럼 보입니다. 모든 정보가 이미 양식에 있으므로 FormDataconstructor을 쉽게 사용하고 양식 요소를 선택할 수 있습니다. 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의 아약스를 사용하고 Formdata는 요청

    이 게시물을 변경됩니다에 잘못된 일을 할 것이다, 그렇지 않은 경우는 false jQuery를에 contentType이와 processData 모두 설정할 필요가있는 경우 json 페이로드에서 파일 업로드를위한 최선의 선택 인 multipart 페이로드까지 ... 대역폭을 더 많이 절약하고 서버를 덜 필요로 함