如何将发布在REST API中的文件上传到Azure存储

时间:2018-07-08 14:50:32

标签: c# .net asp.net-web-api asp.net-web-api2 azure-storage

我需要能够在REACT UI中选择一个文件,然后它将使用发布的文件作为参数之一调用REST服务,然后将其上传到Azure存储

我有这样的东西:

  public async Task<IHttpActionResult>  PutTenant(string id, Tenant tenant, HttpPostedFile certificateFile)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureStorageKey"].ToString());
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference(ConfigurationManager.AppSettings["certificatesContainer"].ToString());

            // Retrieve reference to a blob named "myblob".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");

            // Create or overwrite the "myblob" blob with contents from a local file.
            using (var fileStream = System.IO.File.OpenRead(certificateFile))
            {
                blockBlob.UploadFromStream(fileStream);
            }

            var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
            tenant.CertificatePath = blockBlob.Uri;

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            if (id != tenant.TenantId)
            {
                return BadRequest();
            }

            var added = await tenantStore.AddAsync(tenant);
            return StatusCode(HttpStatusCode.NoContent); 
        }

我不确定openread行是如何获取HttpPostedFile然后上传到Azure存储的。

1 个答案:

答案 0 :(得分:2)

您应该使用内置的HttpPostedFile.InputStream直接上传到blob,并设置blob的文件类型。

用以下内容替换您的using (var fileStream块:

blockBlob.Properties.ContentType = certificateFile.ContentType;
blockBlob.UploadFromStream(certificateFile.InputStream);