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

问题描述 投票:0回答:3

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

  • 学号
  • 姓名
  • 电子邮件地址
  • 家庭住址
  • 联络号码
  • 上传学生照片
  • isActive 标志表明学生是否活跃

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

我该怎么做?

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

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

如何将这两者结合起来,以便我可以上传学生的图像以存储在 blob 中,同时将 URI 返回到学生班级?

asp.net-mvc azure azure-cosmosdb azure-blob-storage document-database
3个回答
0
投票

首先,您需要从azure门户创建azure存储帐户及其下的容器。然后你可以创建如下方法。您可以将文件保存在 azure blob 存储中以唯一文件名命名的文件夹下,并将文件名存储在 SQL 数据库中。可以通过传递目标文件夹信息和唯一文件名来访问保存的文件。

上传文件:

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

下载文件:

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

0
投票

根据最新的方法:

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


-1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.