如何在 asp.net mvc 应用程序中将图片存储在 azure blob 存储中?

How do I store a picture in azure blob storage in asp.net mvc application?

我目前正在开发一个 ASP.Net 存储学生信息的应用程序。我需要存储以下信息:

此信息正在存储在文档数据库中,需要将学生的照片上传到 Azure blob 存储,同时将图像的 link 返回到文档数据库

我该怎么做?

我目前有一个 class 学生信息,如下所示:

public class Student
{
    [Key]
    public int StudentId { get; set; }

    [Required]
    [StringLength(8, MinimumLength = 8)]
    [DisplayName("Student Number")]
    public string StudentNo { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 1)]
    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 1)]
    [DisplayName("Last Name")]
    public string LastName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [DisplayName("Email Address")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, MinimumLength = 5)]
    [DataType(DataType.MultilineText)]
    [DisplayName("Home Address")]
    public string HomeAddress { get; set; }

    [Required]
    [DataType(DataType.PhoneNumber)]
    [StringLength(10)]
    [DisplayName("Mobile No.")]
    public string Mobile { get; set; }

    public bool IsActive { get; set; }
}

我有一个单独的 blob 视图模型,因为我还在试验 blob:

 public class BlobViewModel
{

    public string BlobContainerName { get; set; }
    public string StorageUri { get; set; }
    public string ActualFileName { get; set; }
    public string PrimaryUri { get; set; }
    public string fileExtension { get; set; }

    public string FileNameWithoutExt
    {
        get
        {
            return Path.GetFileNameWithoutExtension(ActualFileName);
        }
    }

    public string FileNameExtensionOnly
    {
        get
        {
            return System.IO.Path.GetExtension(ActualFileName).Substring(1);
        }
    }

我如何将这 2 个结合起来,以便我可以上传图像供学生存储在 blob 中,同时将 URI 返回给学生 class?

使用 Azure CosmosDB 进行存储可能会有所帮助。 使用 CosmosDB,您可以轻松地将图像存储为学生文档的附件:https://docs.microsoft.com/en-us/rest/api/cosmos-db/attachments

如果您不打算使用 CosmosDB,请更准确地说明数据库存储。

首先,您需要从 azure 创建 azure 存储帐户和容器 portal.Then 您可以创建类似 below.You 的方法可以将文件保存在 azure blob 存储中具有唯一文件名的文件夹下并将文件名存储在 SQL database.The 保存的文件可以通过传递目标文件夹信息和唯一文件名来访问。

Updload File:

    public static void UploadBlob(string targetfolder, string fileName, FileStream fileStream)
    {
        try
        {
            if (!string.IsNullOrWhiteSpace(fileName) && fileStream != null)
            {
                string storageConnection = CloudConfigurationManager.GetSetting("your storage connection string");
                CloudStorageAccount StorageAccount = CloudStorageAccount.Parse(storageConnection);
                CloudBlobClient BlobClient = StorageAccount.CreateCloudBlobClient();
                CloudBlobContainer cloudBlobContainer = BlobClient.GetContainerReference("your container name");

                CloudBlockBlob blockBlob = cloudBlobContainer.GetBlockBlobReference(targetFolder + fileName);

                blockBlob.UploadFromStream(fileStream);
            }
        }
        catch (Exception ex)
        {
            throw new Exception("File Upload Failed");
        }
    }

Download File:

    public ActionResult DownloadFile()
        {

            Stream stream =DownloadFilelob(targetFolder,fileName)
            return File(stream, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        }


public Stream DownloadFileBlob(string targetFolder, string fileName)
{
    try
    {
        if (!string.IsNullOrWhiteSpace(fileName))
        {
            string storageConnection = CloudConfigurationManager.GetSetting("your storage connection string");
            CloudStorageAccount StorageAccount = CloudStorageAccount.Parse(storageConnection);
            CloudBlobClient BlobClient = StorageAccount.CreateCloudBlobClient();
            CloudBlobContainer cloudBlobContainer = BlobClient.GetContainerReference("your container name");

            CloudBlockBlob blockBlob = cloudBlobContainer.GetBlockBlobReference(targetFolder + fileName);

    return blockBlob.OpenRead()
        }
    }
    catch (Exception ex)
    {
        throw new Exception("File Download Failed");
    }
}

根据最新的方法:

public static async Task<bool> UploadFileToStorage(Stream fileStream, string fileName, AzureStorageConfig _storageConfig)
    {
        // Create a URI to the blob
        Uri blobUri = new Uri("https://" +
                              _storageConfig.AccountName +
                              ".blob.core.windows.net/" +
                              _storageConfig.ImageContainer +
                              "/" + fileName);

        // Create StorageSharedKeyCredentials object by reading
        // the values from the configuration (appsettings.json)
        StorageSharedKeyCredential storageCredentials =
            new StorageSharedKeyCredential(_storageConfig.AccountName, _storageConfig.AccountKey);

        // Create the blob client.
        BlobClient blobClient = new BlobClient(blobUri, storageCredentials);

        // Upload the file
        await blobClient.UploadAsync(fileStream);

        return await Task.FromResult(true);
    }

您需要下载 nuget 包:Azure.Storage.Blobs 版本 12.X