如何在 DotNetCore 的 Blob 存储中上传多个文件
Posted
技术标签:
【中文标题】如何在 DotNetCore 的 Blob 存储中上传多个文件【英文标题】:How to upload Multiple Files in Blob storage in DotNetCore 【发布时间】:2020-08-10 15:58:05 【问题描述】:当我尝试上传多个文件时,我能够上传单个文本文件,它只需要单个 文件可以有人帮助我如何上传多个文本文件:
public DemoController(IConfiguration configuration)
_configuration = configuration;
我的创建方法:
public async Task<IActionResult> Create(IFormFile files)
string blobstorageconnection = _configuration.GetValue<string>("blobstorage");
byte[] dataFiles;
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("demodata");
BlobContainerPermissions permissions = new BlobContainerPermissions
PublicAccess = BlobContainerPublicAccessType.Blob
;
string systemFileName = files.FileName;
await cloudBlobContainer.SetPermissionsAsync(permissions);
await using (var target = new MemoryStream())
files.CopyTo(target);
dataFiles = target.ToArray();
Console.WriteLine("upload files Successfully");
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(systemFileName);
await cloudBlockBlob.UploadFromByteArrayAsync(dataFiles, 0, dataFiles.Length);
return View();
我的观点:(Create.cs html)
@
ViewData["Title"] = "Create";
<div class="row">
<div class="col-md-6">
<form method="post" enctype="multipart/form-data" asp-controller="Demo" asp-action="Create">
<div class="form-group">
<label> Select File </label>
<input class="form-control" name="files" multiple="multiple" type="file" />
</div>
<div class="form-group">
<input class="btn btn-success" type="submit" value="Submit" id="demo" text="Succcessfully Uploaded" />
</div>
</form>
</div>
【问题讨论】:
【参考方案1】:请尝试以下代码(未经测试的代码):
public async Task<IActionResult> Create(List<IFormFile> files)
string blobstorageconnection = _configuration.GetValue<string>("blobstorage");
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("demodata");
BlobContainerPermissions permissions = new BlobContainerPermissions
PublicAccess = BlobContainerPublicAccessType.Blob
;
await cloudBlobContainer.SetPermissionsAsync(permissions);
foreach (var formFile in files)
byte[] data;
string systemFileName = formFile.FileName;
await using (var target = new MemoryStream())
formFile.CopyTo(target);
data = target.ToArray();
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(systemFileName);
await cloudBlockBlob.UploadFromByteArrayAsync(data, 0, data.Length);
return View();
本质上,这个想法是传递文件集合,然后在您的控制器操作中循环该集合并单独上传每个项目。
【讨论】:
以上是关于如何在 DotNetCore 的 Blob 存储中上传多个文件的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 JAVA 在 Blob 存储容器中一起下载存储在根和子文件夹中的多个文件?
如何使用 .NET v12 SDK 在 Azure Blob 存储中上传具有指定 ContentType 的 Blob?