2017-02-25 51 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(); 

现在文件被正确保存为分析文件。

相关问题