【问题标题】:Upload a Single File to Blob Storage Azure将单个文件上传到 Blob 存储 Azure
【发布时间】:2021-01-04 01:32:45
【问题描述】:

如何使用 C# 上传文件?我需要从 dialogWindow 上传文件。

【问题讨论】:

  • 查看Blob transfer utility 这是一个很棒的项目,全部使用c#。它会告诉你怎么做。
  • 这是GitHub 上的 C# 包装器,它适用于 Azure blob 或 Amazon S3,并支持本地缓存和版本检查。
  • 这个C# Azure Blob Storage Manager class 是一个非常好的基本类文件,如果有人需要一个类用于他们的 C# 项目。

标签: c# azure


【解决方案1】:
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;    

// Retrieve storage account from connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("StorageKey");

// 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);
}

请参阅here 了解所需的 SDK 和参考

我认为这是你需要的

【讨论】:

  • 这在 2018 年仍然有效。只需将 blockBlob.UploadFromStream(fileStream); 替换为 await blockBlob.UploadFromStreamAsync(fileStream);
  • 对于像我这样的新手:“myblob”只是目标文件名。
  • 这些库现在都是遗留的。不要使用此代码
【解决方案2】:

由于 WindowsAzure.Storage 是旧版。使用 Microsoft.Azure.Storage.* 我们可以使用以下代码上传

  static async Task CreateBlob()
    {
        
        BlobServiceClient blobServiceClient = new BlobServiceClient(storageconnstring);
        
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
        
        BlobClient blobClient = containerClient.GetBlobClient(filename);

        
        using FileStream uploadFileStream = File.OpenRead(filepath);
        
        await blobClient.UploadAsync(uploadFileStream, true);
        uploadFileStream.Close();
    }

【讨论】:

    【解决方案3】:

    以下代码 sn -p 是执行文件上传的最简单形式。 我在此代码中添加了几行,以检测上传文件类型并检查容器是否存在。

    注意:- 您需要先添加以下 NuGet 包。

    1. Microsoft.AspNetCore.StaticFiles

    2. Microsoft.Azure.Storage.Blob

    3. Microsoft.Extensions.Configuration

      static void Main(string[] args)
      {
          Console.WriteLine("Hello World!");
          string connstring = "DefaultEndpointsProtocol=https;AccountName=storageaccountnewne9d7b;AccountKey=3sUU8J5pQQ+6YYIi+b5jo+BiSb5XPt027Rve6N5QP9iPEhMXZAbzUfsuW7QDWi1gSPecsPFpC6AzmA9jwPYs6g==;EndpointSuffix=core.windows.net";
          string containername = "newturorial";
          string finlename = "TestUpload.docx";
          var fileBytes = System.IO.File.ReadAllBytes(@"C:\Users\Namal Wijekoon\Desktop\HardningSprint2LoadTest\" + finlename);
      
          var cloudstorageAccount = CloudStorageAccount.Parse(connstring);
          var cloudblobClient = cloudstorageAccount.CreateCloudBlobClient();
          var containerObject = cloudblobClient.GetContainerReference(containername);
      
          //check the container existance
          if (containerObject.CreateIfNotExistsAsync().Result)
          {
              containerObject.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
          }
          var fileobject = containerObject.GetBlockBlobReference(finlename);
      
          //check the file type
          string file_type;
          var provider = new FileExtensionContentTypeProvider();
          if(!provider.TryGetContentType(finlename, out file_type))
          {
              file_type = "application/octet-stream";
          }
      
          fileobject.Properties.ContentType = file_type;
          fileobject.UploadFromByteArrayAsync(fileBytes, 0 , fileBytes.Length);
      
          string fileuploadURI = fileobject.Uri.AbsoluteUri;
          Console.WriteLine("File has be uploaded successfully.");
          Console.WriteLine("The URL of the Uploaded file is : - \n" + fileuploadURI);
      }
      

    【讨论】:

    • CloudStorageAccount 位于 Microsoft.WindowsAzure.Storage,而不是 Microsoft.Azure.Storage。
    【解决方案4】:

    我们可以使用BackgroundUploader类,那么我们需要提供StorageFile对象和一个Uri: 必需的命名空间:

    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.Networking.BackgroundTransfer;
    using Windows.Storage.Pickers;
    using Windows.Storage;
    

    过程是这样的: Uri 是使用通过 UI 输入字段提供的字符串值定义的,当最终用户通过 PickSingleFileAsync 操作提供的 UI 选择文件时,将返回由 StorageFile 对象表示的所需上传文件

    Uri uri = new Uri(serverAddressField.Text.Trim());
    FileOpenPicker picker = new FileOpenPicker();
    picker.FileTypeFilter.Add("*");
    StorageFile file = await picker.PickSingleFileAsync();
    

    然后:

    BackgroundUploader uploader = new BackgroundUploader();
    uploader.SetRequestHeader("Filename", file.Name);
    UploadOperation upload = uploader.CreateUpload(uri, file);
    
    // Attach progress and completion handlers.
    await HandleUploadAsync(upload, true);
    

    就是这样

    【讨论】:

      【解决方案5】:

      这是完整的方法。

       [HttpPost]
              public ActionResult Index(Doctor doct, HttpPostedFileBase photo)
              {
      
                  try
                  {
                      if (photo != null && photo.ContentLength > 0)
                      {
                          // extract only the fielname
                          var fileName = Path.GetFileName(photo.FileName);
                          doct.Image = fileName.ToString();
      
                          CloudStorageAccount cloudStorageAccount = DoctorController.GetConnectionString();
                          CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
                          CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");
      
      
                          string imageName = Guid.NewGuid().ToString() + "-" +Path.GetExtension(photo.FileName); 
      
                          CloudBlockBlob BlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
      
                          BlockBlob.Properties.ContentType = photo.ContentType;
                          BlockBlob.UploadFromStreamAsync(photo.InputStream);
                          string imageFullPath = BlockBlob.Uri.ToString();
      
                          var memoryStream = new MemoryStream();
      
      
                          photo.InputStream.CopyTo(memoryStream);
                          memoryStream.ToArray();
      
      
      
                          memoryStream.Seek(0, SeekOrigin.Begin);
                          using (var fs = photo.InputStream)
                          {
                              BlockBlob.UploadFromStreamAsync(memoryStream);
                          }
      
                      }
                  }
                  catch (Exception ex)
                  {
      
                  }
      
      
                  return View();
              }
      

      getconnectionstring 方法在哪里。

       static string accountname = ConfigurationManager.AppSettings["accountName"];
            static  string key = ConfigurationManager.AppSettings["key"];
      
      
                  public static CloudStorageAccount GetConnectionString()
                  {
      
                      string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountname, key);
                      return CloudStorageAccount.Parse(connectionString);
                  }
      

      【讨论】:

      • 好像这样会上传两次流吧?
      猜你喜欢
      • 2017-01-24
      • 2017-08-19
      • 2011-10-12
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 2019-08-13
      相关资源
      最近更新 更多