adding to azure blob storage with stream

2020-07-25 08:46发布

问题:

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();
    }
}