如何将字节数组(即byte [])保存到Azure Blob存储?

时间:2013-02-27 14:56:43

标签: c# azure azure-storage-blobs

我知道如何保存Streams,但我想获取该流并创建缩略图和其他大小的图像,但我不知道如何将byte []保存到Azure Blob存储。

这就是我现在要保存Stream的内容:

 // Retrieve reference to a blob named "myblob".
        CloudBlockBlob _blockBlob = container.GetBlockBlobReference("SampleImage.jpg");

        // upload from Stream object during file upload
        blockBlob.UploadFromStream(stream);

        // But what about pushing a byte[] array?  I want to thumbnail and do some image manipulation

5 个答案:

答案 0 :(得分:21)

这曾经存在于Storage Client库中(肯定是版本1.7) - 但他们在版本2.0中将其删除了

  

“所有上传和下载方法现在都是基于流的FromFile,   ByteArray,Text重载已被删除。“

http://blogs.msdn.com/b/windowsazurestorage/archive/2012/10/29/windows-azure-storage-client-library-2-0-breaking-changes-amp-migration-guide.aspx

在字节数组周围创建只读内存流非常轻量级:

byte[] data = new byte[] { 1, 2, 3 };
using(var stream = new MemoryStream(data, writable: false)) {
    blockBlob.UploadFromStream(stream);
}

更新:UploadFromByteArray又回来了

MSDN documentation - 从我在the source code中可以看出,这是3.0版本的版本,并且版本4.0仍然存在。

答案 1 :(得分:8)

更新

UploadFromByteArray又回来了。

public void UploadFromByteArray (
    byte[] buffer,
    int index,
    int count,
    [OptionalAttribute] AccessCondition accessCondition,
    [OptionalAttribute] BlobRequestOptions options,
    [OptionalAttribute] OperationContext operationContext
)

http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.blob.cloudblockblob.uploadfrombytearray.aspx

答案 2 :(得分:3)

使用新的SDK azure.storage.blob

var blobContainerClient = new BlobContainerClient(storageConnectionString, containerName);
BlobClient blob = blobContainerClient.GetBlobClient(blobName);

using(var ms = new MemoryStream(data, false))
{
     await blob.UploadAsync(ms);
}

答案 3 :(得分:2)

我对Azure一无所知,但是使用Streams,您可以按照以下方式进行操作:

//byte[] data;

using(var ms = new MemoryStream(data, false))
{
    blockBlob.UploadFromStream(ms);
}

答案 4 :(得分:-1)

这是我目前使用的功能:

//CREATE FILE FROM BYTE ARRAY
public static string createFileFromBytes(string containerName, string filePath, byte[] byteArray)
{

    try {

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings("StorageConnectionString").ConnectionString);



        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference(containerName);

        if (container.Exists == true) {
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(filePath);


            try {
                using (memoryStream == new System.IO.MemoryStream(byteArray)) {
                    blockBlob.UploadFromStream(memoryStream);
                }
                return "";
            } catch (Exception ex) {
                return ex.Message.ToString();
            }
        } else {
            return "Container does not exist";
        }
    } catch (Exception ex) {
        return ex.Message.ToString();
    }
}