2017-02-25 64 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編碼的字符串或字節值數組。

我在做什麼錯,是否有更好的方法?

回答

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(); 

現在文件被正確保存爲分析文件。

相關問題