2017-02-25 5 views
2

Ajax를 사용하여 이미지 파일을 가져 와서이를 구문 분석 파일로 저장하려고합니다. 나는 과정에 새로 온 사람이 내가 지금까지있어 무엇 :구문 분석 url에서 이미지 파일 데이터를 가져 와서 구문 분석 파일로 저장

$.ajax({ 
     type: "GET", 
     url: url, 
     headers:{'Content-Type':'image/jpeg','X-Requested-With':'XMLHttpRequest'}, 
     processData: false, 
     success: function (data) { 

      var name = "photo.jpg"; 
      var img = btoa(encodeURIComponent(data)); 

      var parseFile = new Parse.File(name, { base64: img }); 

      parseFile.save().then(function() { 

       console.log('Saved parse file: ' + parseFile.url()); 

      }, function (error) { 

       console.log("error: " + error.message); 
      }); 
     }, 
     error: function (xhr, ajaxOptions, thrownError) { 

      console.log('error on uploadPhoto: ' + xhr + ' ' + ajaxOptions + ' ' + thrownError); 
     } 
    }); 

[파일 저장하는 것 같지만 내가 할 모든 빈 파일입니다. Parse Docs에서는 base64로 인코딩 된 String 또는 바이트 값 배열을 사용할 수 있다고 말합니다.

내가 잘못하고있는 것은 더 나은 접근 방법입니까?

답변

0

XMLHttpRequest를 사용하여 다른 접근 방식을 사용하기로 결정했습니다. 코드는 다음과 같습니다.

var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 

     if (this.readyState == 4 && this.status == 200) { 

      var reader = new window.FileReader(); 

      reader.readAsDataURL(this.response); 

      reader.onloadend = function() { 

       var name = "photo.jpg"; 

       var base64data = reader.result; 

       var parseFile = new Parse.File(name, {base64: base64data}); 

       parseFile.save().then(function() { 

        console.log('Saved parse file: ' + parseFile.url()); 

       }, function (error) { 

        console.log("error: " + error.message); 
       }); 
      } 
     } 
    }; 

    xhr.open('GET', url); 
    xhr.responseType = 'blob'; 
    xhr.send(); 

이제 파일이 구문 분석 파일로 올바르게 저장됩니다.