【问题标题】:How to upload a file directly to azure blob from the URL in c#?如何从 c# 中的 URL 将文件直接上传到 azure blob?
【发布时间】:2021-01-01 03:44:05
【问题描述】:

我有一个类似于“https://XXXXXXXX-functions.azurewebsites.net/api/UploadedZIPFile?ticket=1234&code=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”的网址,其中包含该文件。 “UploadedZIPFile”是文件名。在 URL 中,我没有文件名的扩展名。将文件下载到我的系统后,它会显示扩展名。我想将来自 URL 的文件上传到 Azure blob 存储。如何使用 c# 将文件从给定的 URL 上传到 azure blob 存储?请在下面添加我的代码示例

public async Task<string> automaticFileUpload(string ticketNum, string type, string fileURL) 
        {
            Uri uri = new Uri(fileURL);
            string fileName = System.IO.Path.GetFileName(uri.LocalPath);
            string extension = ".zip";
            string finalFileName = fileName + extension;

            

            var connectionString = "xxxxxxx";

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer cloudBlobContainer =
                cloudBlobClient.GetContainerReference("xxxxxxx");
            await cloudBlobContainer.CreateIfNotExistsAsync();
            BlobContainerPermissions permissions = new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            };
            await cloudBlobContainer.SetPermissionsAsync(permissions);
            if (!cloudBlobContainer.GetPermissionsAsync().Equals(BlobContainerPublicAccessType.Off))
            {
                await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Off
                });
            }

            CloudBlockBlob blockblob = cloudBlobContainer.GetBlockBlobReference(finalFileName);
            blockblob.Properties.ContentType = "application/zip";

            using (var client = new HttpClient())
            {
                //get the url 
                var request = new HttpRequestMessage(HttpMethod.Get, fileURL);
                var sendTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
                var response = sendTask.Result;

                HttpStatusCode status = response.StatusCode;
                if (status == HttpStatusCode.OK)
                {
                    var httpStream = response.Content.ReadAsStreamAsync().Result;
                    MemoryStream ms = new MemoryStream();
                    httpStream.CopyTo(ms);
                    ms.Position = 0;
                    await blockblob.UploadFromStreamAsync(ms);
                   
                    return blockblob.Uri.AbsoluteUri;
                }
            }

            return null;
 }

到目前为止,我正在为文件扩展名和内容类型采用硬编码值但我需要动态值

提前致谢

【问题讨论】:

  • 你尝试了什么?如果您对代码有具体问题,我们可以为您提供帮助。如果您已经尝试过,请分享您的尝试。不幸的是,我们不是一群编写您的软件的程序员
  • 对不起,我添加了我的代码示例
  • 您是在问如何检测上传文件的扩展名和内容类型?当您运行 HTTP GET 请求将该文件下载到您的程序中时,您应该能够从 HTTP 响应标头中获取内容类型。从中您可以派生一个合适的扩展名(如果带有扩展名的文件名也未包含在响应标头中)。

标签: c# asp.net azure-blob-storage webapi


【解决方案1】:

您可以在响应标头中获取content-type,请参阅:

然后从这个way的内容类型中获取文件extension

有使用 HttpWebResponse 获取标头的代码。详情请见document

// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

// Displays all the headers present in the response received from the URI.
Console.WriteLine("\r\nThe following headers were received in the response:");
// Displays each header and it's key associated with the response.
for(int i=0; i < myHttpWebResponse.Headers.Count; ++i)
    Console.WriteLine("\nHeader Name:{0}, Value :{1}",myHttpWebResponse.Headers.Keys[i],myHttpWebResponse.Headers[i]);
// Releases the resources of the response.
myHttpWebResponse.Close();

【讨论】:

  • 谢谢你 Pamela Peng。它对我有很大帮助
猜你喜欢
  • 2021-06-07
  • 2019-05-21
  • 2016-07-24
  • 2013-03-18
  • 2012-08-14
  • 2019-04-10
  • 1970-01-01
  • 2015-08-27
  • 2011-11-02
相关资源
最近更新 更多