2017-02-16 65 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,抱歉没有帮助:) –