从 Xamarin.Forms PCL 上传到 Azure Blob

Upload to Azure Blob from Xamarin.Forms PCL

我正在尝试使用 WindowsAzure.Storage 7.0.2-preview 从 Xamarin.Forms PCL 应用程序将图像流上传到 Azure Blob。出于某种原因,StorageCredentials 无法识别 SAS 令牌的 AccountName。

var credentials = new StorageCredentials("https://<ACCOUNT-NAME>.blob.core.windows.net/...");
CloudStorageAccount Account = new CloudStorageAccount(credentials, true);

然后像这样上传:

 public async Task<string> WriteFile(string containerName, string fileName, System.IO.Stream stream, string contentType = "")
    {
        var container = GetBlobClient().GetContainerReference(containerName);
        var fileBase = container.GetBlockBlobReference(fileName);
        await fileBase.UploadFromStreamAsync(stream);
        if (!string.IsNullOrEmpty(contentType))
        {
            fileBase.Properties.ContentType = contentType;
            await fileBase.SetPropertiesAsync();
        }
        return fileBase.Uri.ToString();
    }

如何解决我的问题?有没有更好的上传到 Azure 存储的解决方案? 谢谢!

接受 SAS 令牌的 StorageCredentials 构造函数只需要 SAS 令牌的查询部分,而不是完整的 URI 字符串。如果您拥有资源的完整 URI(包括 SAS 令牌),最常见的做法是直接使用该对象的构造函数。例如,如果您有 URI:

string myBlobUri = @"https://myaccount.blob.core.windows.net/sascontainer/sasblob.txt?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D";

您可以像这样创建一个 blob 对象:

CloudBlockBlob fileBase = new CloudBlockBlob(new Uri(myBlobUri));

如果您出于某种原因确实想要使用 StorageCredentials 和 CloudStorageAccount 类(例如,您可能有一个 AccountSAS),这里有一种方法可以实现:

string sasToken = @"sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D";
StorageCredentials credentials = new StorageCredentials(sasToken);
CloudStorageAccount account = new CloudStorageAccount(credentials, "myaccount", "core.windows.net", true)