Azure云存储SDK UploadFromStreamAsync不起作用

时间:2018-07-08 15:28:57

标签: c# azure asp.net-core azure-storage-blobs

我正在尝试将文件上传到.Net Core 2.1中的Azure blob存储。下面是我的代码。

layoutChanged

View的实现-

myView.on("layoutChanged", function(){
    console.log("layout change");
});

代码执行时出现以下错误-

  

{System.ObjectDisposedException:无法访问关闭的文件。在   System.IO.FileStream.get_Position()在   Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream.get_Position()   在   Microsoft.AspNetCore.Http.Internal.ReferenceReadStream.VerifyPosition()   在   Microsoft.AspNetCore.Http.Internal.ReferenceReadStream.ReadAsync(Byte []   缓冲区,Int32偏移量,Int32计数,CancellationToken   cancelToken)   Microsoft.WindowsAzure.Storage.Core.Util.StreamExtensions.WriteToAsync [T](流   stream,Stream toStream,IBufferManager bufferManager,Nullable IFormFileCollection files = formCollection.Files; foreach (var file in files) { if (file.Length > 0) { _azureCloudStorage.UploadContent(cloudBlobContainer, file.OpenReadStream(), file.FileName); } } 1 maxLength,布尔值calculateMd5,   ExecutionState UploadContent 1的长度,AccessCondition accessCondition,   BlobRequestOptions选项,OperationContext operationContext,   IProgress public async void UploadContent(CloudBlobContainer containerReference, Stream contentStream, string blobName) { try { using (contentStream) { var blockBlobRef = containerReference.GetBlockBlobReference(blobName); //await containerReference.SetPermissionsAsync(new BlobContainerPermissions //{ // PublicAccess = BlobContainerPublicAccessType.Blob //}); await blockBlobRef.UploadFromStreamAsync(contentStream); } } catch(Exception ex) { //Error here } } 1长度,AccessCondition accessCondition,   BlobRequestOptions选项,OperationContext operationContext,   C:\ Program Files中的CancellationToken cancelToken)   (x86)\ Jenkins \ workspace \ release_dotnet_master \ Lib \ WindowsRuntime \ Blob \ CloudBlockBlob.cs:line   290位于Common.AzureCloudStorage.UploadContent(CloudBlobContainer   containerReference,Stream contentStream,字符串blobName)

对我有用的替代解决方案: adding to azure blob storage with stream

对此有任何帮助吗?如果可以提供更多详细信息,请告诉我。

4 个答案:

答案 0 :(得分:1)

我的解决方案是包括文件长度并设置位置= 0。

MemoryStream outStr = new MemoryStream();
CloudBlockBlob myBlob = container.GetBlockBlobReference(name);
outStr.Position = 0;
await myBlob.UploadFromStreamAsync(outStr, outStr.Length);

答案 1 :(得分:0)

我的解决方案是等任务完成后再继续,例如

    private async void SaveAsync(IFormFile file)
    {
        CloudBlockBlob blob = this.blobContainer.GetBlockBlobReference(file.FileName);
        var task = blob.UploadFromStreamAsync(file.OpenReadStream(), file.Length);

        while (task.IsCompleted == false) {
            Thread.Sleep(1000);
        }

    }

也许传递长度也有帮助吗?

答案 2 :(得分:0)

几年后出现相同问题(WindowsAzure.Storage版本3.0.3.0,targetFramework net45)。
同步的 UploadFromStream 有效,而 UploadFromStreamAsync 无效。 我会投票怀疑Azure SDK不会磨练异步版本,而不是sdk使用不足。而且,我还是一位经验丰富的开发人员-经验丰富,不时会偶然发现已声明的Microsoft功能,但仔细检查后将无法使用。
对于其他异步方法(例如 SetPropertiesAsync ),此处也是如此。我一直在调试我的方法(如下),并且在每个* Async 方法之后都只是失去了断点-这就是我弄清楚的方式。出于好奇,将 UploadFromStreamAsync => UploadFromStream ,然后将 SetPropertiesAsync 更改为 SetProperties

    public async Task StoreItem(string filename, MemoryStream content, string contentType, ICloudBlob cloudBlob)
{
    cloudBlob.UploadFromStream(content); //this line works
    //await cloudBlob.UploadFromStreamAsync(content); //doesn't work
    cloudBlob.Properties.ContentType = contentType;
    cloudBlob.SetProperties();
    //await cloudBlob.SetPropertiesAsync(); //doesn't work either
}

答案 3 :(得分:-1)

我已经测试了您的方法UploadContent,效果很好。

我想您的问题可能出在您的文件收集上。

这是我的代码供您参考:

using ConsoleAppCore.DAL;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using System;
using System.IO;

namespace ConsoleAppCore
{
    class Program
    {
        static void Main(string[] args)
        {
            Run();
            Console.WriteLine("Success");
            Console.ReadLine();
        }

        public static void Run()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=xxxxx;AccountKey=O7xB6ebGq8e86XQSy2vkvSi/x/exxxxxxxxxxkly1DsQPYY5dF2JrAVHtBozbJo29ZrrGJA==;BlobEndpoint=https://xxxx.blob.core.windows.net/;QueueEndpoint=https://xxxx.queue.core.windows.net/;TableEndpoint=https://xxxx.table.core.windows.net/;FileEndpoint=https://xxxx.file.core.windows.net/;");

            CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = cloudBlobClient.GetContainerReference("containertest");

            container.CreateIfNotExists();
            DirectoryInfo dir = new DirectoryInfo("E://Test");

            foreach (FileInfo file in dir.GetFiles())
            {

                BlobStorage.UploadContent(container, file.OpenRead(), file.Name);

            }
        }


    }
}

还有我的UploadContent类中的BlobStorage方法:

using Microsoft.Azure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ConsoleAppCore.DAL
{
    public class BlobStorage
    {
        public static async void UploadContent(CloudBlobContainer containerReference, Stream contentStream, string blobName)
        {
            try
            {
                using (contentStream)
                {

                    var blockBlobRef = containerReference.GetBlockBlobReference(blobName);
                    //await containerReference.SetPermissionsAsync(new BlobContainerPermissions
                    //{
                    //    PublicAccess = BlobContainerPublicAccessType.Blob
                    //});
                    await blockBlobRef.UploadFromStreamAsync(contentStream);
                }
            }
            catch (Exception ex)
            {
                //Error here
            }
        }
    }
}