Azure Cloud Storage SDK UploadFromStreamAsync存储0字节

时间:2019-05-15 17:06:25

标签: .net asp.net-mvc azure asp.net-core azure-storage

我正在使用ASP.NET Core 2.1 Azure云存储SDK UploadFromStreamAsync方法将流上传为天蓝色的blob。已创建Blob,但大小显示0个字节。下面是我的代码。有人可以告诉我我是否想念东西吗?

   [HttpPost]
        public async Task<IActionResult> PostRecordedAudioVideo()
        {
            var file = Request.Form.Files[0];

            if (file.Length > 0)
            {
                var stream = new MemoryStream();

                await this.Request.Body.CopyToAsync(stream);

                CloudStorageAccount storageAccount = null;
                CloudBlobContainer cloudBlobContainer = null;

                string storageConnectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

                if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
                {   
                        CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
                        cloudBlobContainer = cloudBlobClient.GetContainerReference("screening-videos");
                        CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference("TestBlobName");
                        await cloudBlockBlob.UploadFromStreamAsync(stream);
                }
            }
            return Json("Success or failure response");
        }

1 个答案:

答案 0 :(得分:1)

我已经对它进行了测试。确实如此,您需要在上传之前将流位置设置为0。 下面是我的示例代码,效果很好。

 static void Main(string[] args)
    {

        var stream = new MemoryStream();
        var sw = new StreamWriter(stream);
        sw.Write("adiojaihdhwjfoewjfioghauhfjowpf");
        sw.Flush();

        stream.Position = 0;

        UploadfromstreamAsync(stream).Wait();
    }

    static async System.Threading.Tasks.Task UploadfromstreamAsync(MemoryStream stream)
    {
        CloudStorageAccount storageAccount = null;
        CloudBlobContainer cloudBlobContainer = null;

        string storageConnectionString = "connectionstring";

        if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
        {
            CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
            cloudBlobContainer = cloudBlobClient.GetContainerReference("123");
            CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference("TestBlobName2");
            await cloudBlockBlob.UploadFromStreamAsync(stream);
        }
    }