C# 如何从ASP.NET核心应用程序将映像上载到Azure blob存储中的特定目录?

C# 如何从ASP.NET核心应用程序将映像上载到Azure blob存储中的特定目录?,c#,azure,asp.net-core,azure-storage-blobs,C#,Azure,Asp.net Core,Azure Storage Blobs,我想将一个图像上传到blob存储容器中的特定子目录,但我不知道该怎么做。查看文档后,我可以看到,GetBlobs()上有一个重载,允许您指定前缀,但我看不到用于上载的前缀。这是我处理这个问题的方法 上传位置为:uploads/car/17999/ CarController.cs using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; [HttpPost] [ValidateAntiForgeryToken] public IA

我想将一个图像上传到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);
    }

请尝试更改您的
文件名
,并在此处添加
路径前缀
。比如:

string blobName = "car/17999/car-image.jpg";
containerClient.UploadBlob(blobName , car.ImageFile.OpenReadStream());
这将在
car/17999
虚拟文件夹中上载图像

另一种选择是使用和使用其方法:


哇,我当时真是想得太多了。在我之前的代码中使用了前缀来获取数据,我认为这里也必须使用前缀。两方面都很好。是的:)。基本思想是Azure Blob实际上没有文件夹。您的blob的名称实际上是
car/17999/car image.jpg
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());