我想使用angularJS提供的XHR
服务通过$http
下载图像文件,并将响应数据(图像数据)上传到OSS(这是阿里巴巴提供的托管文件服务) )它的api reference for put是:
表示将{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");
}
)
这会产生类型错误:
答案 0 :(得分: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}}" >