在Azure Blob存储中获取图像

时间:2014-02-25 12:34:29

标签: c# xaml azure microsoft-metro

有很多关于将图像文件上传到azure blob的教程,我已成功将图像文件上传到blob容器,现在我的问题是如何获取它,这是我的代码:

var bitmapImage = new BitmapImage();
bitmapImage.UriSource = new Uri("http://sweetapp.blob.core.windows.net/userprofiles/"+imagename,UriKind.RelativeOrAbsolute);
imgProf.Source = bitmapImage;
我做错了吗?或者是在显示它之前需要做的事情?任何答案将不胜感激!

更新

这是适合我的代码

上载:

            var credentials = new StorageCredentials("sweetapp","[my key]");
            var client = new CloudBlobClient(new Uri("http://sweetapp.blob.core.windows.net/"), credentials);   
            var container = client.GetContainerReference("userprofiles");
            await container.CreateIfNotExistsAsync(); 
            var perm = new BlobContainerPermissions();
            perm.PublicAccess = BlobContainerPublicAccessType.Blob;
            var blockBlob = container.GetBlockBlobReference(imgName);
            using (var fileStream = await file.OpenSequentialReadAsync())
            {
            await blockBlob.UploadFromStreamAsync(fileStream);
           }

获取图片:

     var bitmapImage = new BitmapImage();
     bitmapImage.UriSource = new Uri("http://sweetapp.blob.core.windows.net/userprofiles/"+imagename,UriKind.RelativeOrAbsolute);
     imgProf.Source = bitmapImage;

2 个答案:

答案 0 :(得分:1)

你的代码似乎很好。尝试收听ImageFailedImageOpened事件以确定它是否真的失败,或者只是花些时间加载:

var bitmapImage = new BitmapImage();
........
bitmapImage.ImageOpened += (sender, args) =>
                       {
                           MessageBox.Show("Image opened");
                       };
bitmapImage.ImageFailed += (sender, args) =>
                       {
                           MessageBox.Show("Image failed");
                       };

答案 1 :(得分:1)

请检查blob容器上的ACL。我相信你得到的错误是因为容器的ACL设置为Private(这是默认的ACL)。要使上述代码生效,容器的访问级别应为BlobContainer。您可能会发现此链接对于了解blob容器上的各种ACL选项非常有用:http://msdn.microsoft.com/en-us/library/windowsazure/dd179354.aspx

尝试以下代码获取/设置容器的ACL:

    storageAccount = new CloudStorageAccount(new StorageCredentials("accountname", "accountkey"), false);
    var container = storageAccount.CreateCloudBlobClient().GetContainerReference("containername");
    //Get the container permission
    var permissions = container.GetPermissions();
    Console.WriteLine("Container's ACL is: " + permissions.PublicAccess);
    //Set the container permission to Blob
    container.SetPermissions(new BlobContainerPermissions()
    {
        PublicAccess = BlobContainerPublicAccessType.Blob,
    });