无法在ASP.NET MVC中显示S3存储桶中的上传图像

时间:2019-03-23 11:25:47

标签: angularjs asp.net-mvc amazon-s3 base64

我尝试在asp.net mvc中显示s3存储桶中的图像,我得到了base64编码的响应。但不会在视图中显示图像

第一张图片采用二进制编码,而不是Base64。 所以我用这个转换成base64  函数_arrayBufferToBase64()

这是我的观点

   <img data-ng-src="data:image/jpeg;charset=utf-8;base64,{{str}}" 
   alt="MyImage">  

这是我的MVC控制器

   [HttpGet]
    public ActionResult GetReadObject()
    {
        string responseBody = "";
        try
        {
            using (IAmazonS3 s3client = new AmazonS3Client(_awsAccessKey, _awsSecretKey, RegionEndpoint.USEast1))
            {
                GetObjectRequest request = new GetObjectRequest
                {
                    BucketName = _bucketName,
                    Key = keyName
                };
                using (GetObjectResponse response = s3client.GetObject(request))
                using (Stream responseStream = response.ResponseStream)
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string title = response.Metadata["x-amz-meta-title"];
                    Console.WriteLine("The object's title is {0}", title);

                    responseBody = reader.ReadToEnd();
                }
            }

        }
        catch (Exception ex)
        {

        }

        return Json(responseBody, JsonRequestBehavior.AllowGet);
    }

这是我的控制人

app.controller('myCtrl', function ($scope, $http) {
 $http({
    method: 'GET',
    url: '/User/Dashboard/GetReadObject',
    responseType: 'arraybuffer'
   }).then(function (response) {
    alert("1");
    console.log(response);
    var str = _arrayBufferToBase64(response.data);
    $scope.getImage = str;
    alert(str);
    console.log(str);
    // str is base64 encoded.
},
   function (response) {
    console.error('error in getting static img.');
});


function _arrayBufferToBase64(buffer) {
    var binary = '';
    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
}
})

1 个答案:

答案 0 :(得分:0)

您应该尝试

<img data-ng-src="data:image/jpeg;charset=utf-8;base64,{{getImage}}" 
   alt="MyImage">

正如您在控制器中提到的那样,str是简单的javascript变量,您无法将其与View一起使用。在将str值分配给$ scope.getImage ($ scope.getImage = str)时,可以在视图中使用{{getImage}}和角度表达式。