c# - 如何从 ASP.NET Core 应用程序将图像上传到 Azure Blob 存储中的特定目录?

标签 c# azure asp.net-core azure-blob-storage

我想将图像上传到我的 blob 存储容器中的特定子目录,但我不知道该怎么做。查看文档后,我可以看到,GetBlobs() 上有一个重载,它允许您指定前缀,但我看不到用于上传的前缀。这是我处理这个问题的方法。

上传位置为:uploads/car/17999/

CarController.cs

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Car car)
{
    // Define the cancellation token.
    CancellationTokenSource source = new CancellationTokenSource();
    CancellationToken token = source.Token;

    if (ModelState.IsValid)
    {
        _carService.InsertCar(car);

        int id = car.Id;
        string pathPrefix = "car/17999";
        string fileName = "car-image.jpg";
        string strContainerName = "uploads";

        BlobServiceClient blobServiceClient = new BlobServiceClient(accessKey);
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(strContainerName);

        //An example of how I would GET the blobs from a prefixed location, I don't know how to apply this to the upload part
        //var blobs = containerClient.GetBlobs(0, 0, pathPrefix);

        var blobs = containerClient.UploadBlob(fileName, car.ImageFile.OpenReadStream());
            return RedirectToAction(nameof(Index));
        }            
        return View(car);
    }

最佳答案

请尝试更改您的fileName 并在其中添加pathPrefix。像这样的东西:

string blobName = "car/17999/car-image.jpg";
containerClient.UploadBlob(blobName , car.ImageFile.OpenReadStream());

这应该将图像上传到 car/17999 虚拟文件夹中。

其他选择是使用 BlockBlobClient并使用其 Upload方法:

var connectionString = "UseDevelopmentStorage=true";
var containerName = "uploads";
var blobName = "car/17999/car-image.jpg";
BlockBlobClient blockBlobClient = new BlockBlobClient(connectionString, containerName, blobName);
blockBlobClient.Upload(car.ImageFile.OpenReadStream());

关于c# - 如何从 ASP.NET Core 应用程序将图像上传到 Azure Blob 存储中的特定目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61056490/

相关文章:

c# - 指定 Azure Function 中使用 CloudQueue 类型的存储帐户的名称

azure - azure 上的 umbraco 中的 url 重写

asp.net-core - 如何使用 Entity Framework 核心更新与普通 SQL 更新查询相同的多条记录列表?

c# - LINQ to XML - 从文件加载 XML 片段

c# - 如何防止 ASP.NET Core 在空请求主体上将模型状态标记为无效?

python - 从资源对象 Azure SDK Python 获取资源组名称

asp.net-core - Asp.Net 5 (Mvc 6) 中的 Custom ClaimsPrincipal

asp.net - 无法从 docker 支持的 asp.net core 项目连接到 sql server

C#:WinRT 中的托管扩展性框架

c# - 在运行时向 GroupBox 添加控件