【问题标题】:How to upload a file in to azure blob in Asp.Net Core?如何在 Asp.Net Core 中将文件上传到 azure blob?
【发布时间】:2018-05-09 07:11:38
【问题描述】:

我已尝试使用以下代码将文件上传到我的 azure blob

  public async void UploadSync(IEnumerable<IFormFile> files, string path)
        {
            string MyPath = path.Replace("https://browsercontent.blob.core.windows.net/blob1/", "");

            try
            {
                foreach (var file in files)
                {
                    var newBlob = container.GetBlockBlobReference(MyPath);
                    await newBlob.UploadFromFileAsync(@"C:\Users\joy\Downloads\" + file.FileName);

                }
            }
            catch (Exception ex)
            { throw ex;}

        }

实际上我已经上传了 jpg 文件,但它以“应用程序/八进制蒸汽”类型上传。如何解决?

我的情况是在上传文件时,Windows 资源管理器将打开以选择要上传的文件。因此,如果我们提供如下静态路径,

newBlob.UploadFromFileAsync(@"C:\Users\joy\Downloads\" + file.FileName);

不适用于申请。如何更改此代码以从各个位置上传文件?

【问题讨论】:

    标签: c# azure azure-storage azure-blob-storage


    【解决方案1】:

    尝试使用 UploadFromStream 并告诉我结果

    // Retrieve storage account from connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
        CloudConfigurationManager.GetSetting("StorageConnectionString"));
    
    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
    // Retrieve reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
    
    // 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(@"path\myfile"))
    {
        blockBlob.UploadFromStream(fileStream);
    } 
    

    https://docs.microsoft.com/en-us/azure/storage/blobs/storage-dotnet-how-to-use-blobs

    【讨论】:

    • 您可以通过设置 blockblob.Properties.ContentType 属性来更新您的答案,以考虑 OP 对“应用程序/八进制流”内容类型的关注
    • @sumanth,您的代码运行良好。谢谢。同样,我如何从 azure blob 存储下载文件?您能否分享从 asp.net core 中的 azure blob 下载文件的代码块
    猜你喜欢
    • 2017-11-16
    • 2021-12-18
    • 2019-03-04
    • 2017-03-14
    • 2016-11-11
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多