[英]How do I upload an image to a specific directory in my Azure blob storage from my ASP.NET Core application?
I would like to upload an image to a specific subdirectory within my blob storage container and I'm not sure how to do it.我想将图像上传到我的 blob 存储容器中的特定子目录,但我不知道该怎么做。 Having looked at the documentation I can see that, there is an overload on the
GetBlobs()
which allows you to specify a prefix but I can't see one for uploading.查看文档后,我可以看到,
GetBlobs()
上有一个重载,它允许您指定一个前缀,但我看不到要上传的前缀。 Here is my method that handles this.这是我处理这个问题的方法。
Upload location would be: uploads/car/17999/上传位置为:uploads/car/17999/
CarController.cs汽车控制器.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);
}
Please try by changing your fileName
and prepend the pathPrefix
there.请尝试更改您的文件名并在
pathPrefix
fileName
Something like:就像是:
string blobName = "car/17999/car-image.jpg";
containerClient.UploadBlob(blobName , car.ImageFile.OpenReadStream());
This should upload the image in car/17999
virtual folder.这应该将图像上传到
car/17999
虚拟文件夹中。
Other alternative would be to use BlockBlobClient
and use its Upload
method:其他替代方法是使用
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.