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

How to upload a file posted in REST API to Azure Storage

我需要能够 select 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 存储。

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

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

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