问题描述
我正在尝试将通过.net核心Web API接收到的IFormFile
添加到azure blob存储中.这些是我设置的属性:
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);
现在我像这样使用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);
这给了我以下错误:
内部异常 ObjectDisposedException:无法访问关闭的Stream.
Inner Exception ObjectDisposedException: Cannot access a closed Stream.
调试时,我甚至在fileStream.Position = 0
之前就已经注意到它的位置已经为0.但是,由于出现了此错误,因此我添加了这一行.同样在等待行,fileStream
的_disposed
设置为false.
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.
此外,关于Blob连接,我尝试为字符串常量AccessKey
设置无效的值,并且它显示出完全相同的错误.这意味着我什至不知道它是否是连接.我已经在调试器中检查了blobBlock
中的所有值,但是我不知道如何验证它是否已连接.
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.
推荐答案
尝试直接从流中写入时似乎存在一些问题.我能够通过将流转换为字节数组来运行代码.
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);
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();
}
}
这篇关于通过流添加到Azure Blob存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!