adding to azure blob storage with stream

社会主义新天地 提交于 2019-12-22 12:31:31

问题


I am trying to add an IFormFile received via a .net core web API to an azure blob storage. These are the properties I have set up:

static internal CloudStorageAccount StorageAccount => 
    new CloudStorageAccount(new StorageCredentials(AccountName, AccessKey, AccessKeyName), true);

// Create a blob client.
static internal CloudBlobClient BlobClient => StorageAccount.CreateCloudBlobClient();

// Get a reference to a container 
static internal CloudBlobContainer Container(string ContainerName) 
                        => BlobClient.GetContainerReference(ContainerName);

static internal CloudBlobContainer ProfilePicContainer 
        => Container(ProfilePicContainerName);

Now I use the ProfilePicContainer like this:

var Container = BlobStorage.ProfilePicContainer;
string fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(ProfileImage.FileName);
var blockBlob = Container.GetBlockBlobReference(fileName);
var fileStream = ProfileImage.OpenReadStream();
fileStream.Position = 0;
await blockBlob.UploadFromStreamAsync(fileStream);

This gives me the following error:

Microsoft.WindowsAzure.Storage.StorageException: 'Cannot access a closed Stream.'

Inner Exception ObjectDisposedException: Cannot access a closed Stream.

When debugging, I have noticed even before fileStream.Position = 0 it's position is already 0. However I added the line since I was getting this error. Also right at the await line, the fileStream's _disposed is set to false.

Moreover regarding the blob connection I have tried setting an invalid value for the string constant AccessKey and it shows the exact same error. Which means I have no idea if it is even connection. I have checked all values within blobBlock in the debugger, but I have no idea how to verify if it is connected.


回答1:


There seems to be some issue when trying to write directly from the stream. I was able to run the code by converting the stream to a byte array.

await blockBlob.UploadFromByteArrayAsync(ReadFully(fileStream, blockBlob.StreamWriteSizeInBytes),
                            0, (int)fileStream.Length);

The ReadFully was a modification over this answer https://stackoverflow.com/a/221941

static byte[] ReadFully(Stream input, int size)
{
    byte[] buffer = new byte[size];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, size)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}


来源:https://stackoverflow.com/questions/47296020/adding-to-azure-blob-storage-with-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!