我正在尝试将通过.net核心Web API收到的IFormFile
添加到azure blob存储中。这些是我设置的属性:
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);
现在我像这样使用ProfilePicContainer
:
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);
这给了我以下错误:
Microsoft.WindowsAzure.Storage.StorageException:'无法访问已关闭的流。'
内部例外 ObjectDisposedException:无法访问已关闭的Stream。
调试时,我注意到fileStream.Position = 0
之前它的位置已经为0.但是我添加了这条线,因为我收到了这个错误。同样在等待线上,fileStream
' s _disposed
设置为false。
此外,关于blob连接,我尝试为字符串常量AccessKey
设置无效值,并显示完全相同的错误。这意味着我不知道它是否连接。我已经检查了调试器中blobBlock
内的所有值,但我不知道如何验证它是否已连接。
答案 0 :(得分:1)
尝试直接从流中编写时似乎存在一些问题。我能够通过将流转换为字节数组来运行代码。
await blockBlob.UploadFromByteArrayAsync(ReadFully(fileStream, blockBlob.StreamWriteSizeInBytes),
0, (int)fileStream.Length);
ReadFully
是对此答案的修改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();
}
}