2017-02-16 67 views
0

我想通過XHR使用angularJS提供的$http服務下載一個圖像文件,並上傳響應數據(圖像數據)OSS(它是由阿里巴巴提供的主機文件服務),它的api reference for put是:

enter image description here

這表明,這將需要一個{String|Buffer|ReadStream}作爲第二個參數file, 但如何可以傳輸的響應數據,這樣我可以做出此put(name, file)方法類似的參數:

$http.get("http://image.url/file.gif").then(
    function success(response){ 
     console.log("type of response.data is :" + typeof response.data); 
     oss.put("test.jpg", response.data); //<-- here will give an error 
    }, 
    function fail(response){ 
     console.log("error"); 
    } 
) 

這會給類型錯誤:

enter image description here 任何建議或答案是表示讚賞。

回答

0

如果您通過鏈接始終獲取圖像,並且希望從中獲取字符串數據,我嘗試了一個小函數,希望它有所幫助,它將鏈接並提供給您以base64字符串格式

function getBase64StringFromImgLink(imageSrc, imgType) { 

    var imageAsCanvas; 

    /* 
    * Creates a new image object from the src 
    * Uses the deferred pattern 
    */ 
    var createImage = function() { 
     var deferred = $.Deferred(); 
     var img = new Image(); 

     img.onload = function() { 
      deferred.resolve(img); 
     }; 
     img.src = imageSrc; 
     return deferred.promise(); 
    }; 

    /* 
    * Create an Image, when loaded and start to resize 
    */ 
    $.when(createImage()).then(function (image) { 
     imageAsCanvas = document.createElement("canvas"); 
     imageAsCanvas.width = image.width; 
     imageAsCanvas.height = image.height; 
     var ctx = imageAsCanvas.getContext("2d"); 
     ctx.drawImage(image, 0, 0, imageAsCanvas.width, imageAsCanvas.height); 

     $scope.$apply(function($scope){ 
      $scope.imageAsBase64String = imageAsCanvas.toDataURL(imgType); 
      oss.put("test.jpg", $scope.imageAsBase64String); //<-- here will be the data string i hope it works 
     }); 
    }, function() {console.log('error creating an image')}); 
} 
//How to call example 
getBase64StringFromImgLink('images/george-avatar.jpg', 'image/jpeg'); 

<!--HTML --> 
<img data-ng-src="{{imageAsBase64String}}" > 
+0

謝謝回答,遺憾的是圖像數據,圖像我想獲取和上傳的是'gif',在這種情況下看來,雖然從檢索數據的畫布不會幫助,謝謝: - ) – armnotstrong

+0

np,抱歉沒有幫助:) –