gpt4 book ai didi

c# - azure 函数将多个文件上传到 blob 存储

转载 作者:行者123 更新时间:2023-12-02 08:13:36 24 4
gpt4 key购买 nike

 public static class FileUpload
{
[FunctionName("FileUpload")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
{
string Connection = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
string containerName = Environment.GetEnvironmentVariable("ContainerName");
Stream myBlob = new MemoryStream();
var file = req.Form.Files["File"];
myBlob = file.OpenReadStream();
var blobClient = new BlobContainerClient(Connection, containerName);
var blob = blobClient.GetBlobClient(file.FileName);
await blob.UploadAsync(myBlob);
return new OkObjectResult("file uploaded successfylly");
}
}

这对于上传单个文件来说是可以的。使用azure功能提供多个文件上传的最佳解决方案是什么。

最佳答案

我已经在我的环境中重现并得到了以下预期结果:

首先,我的文件夹中有 3 个文件,如下所示:

enter image description here

upload_ToBlob 方法:

public class AzureBlobSample
{
public void upload_ToBlob(string fileToUpload, string containerName)
{
Console.WriteLine("Inside upload method");

string file_extension,
filename_withExtension;
Stream file;

string connectionString = @"BlobEndpoint=https://rithwik1.blob.core.windows.net/;QueueEndpoint=https://rithwik1.queue.core.windows.net/;FileEndpoint=https://rithwik1.file.core.windows.net/;TableEndpoint=https://rithwik1.table.core.windows.net/;SharedAccessSignature=sv=2=2023-01-05T1Z&st=2023-01-0n3Cs%3D";

file = new FileStream(fileToUpload, FileMode.Open);

CloudStorageAccount cloudStorageAcct = CloudStorageAccount.Parse(connectionString);
CloudBlobClient blobClient = cloudStorageAcct.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(containerName);

if (container.CreateIfNotExists())
{

container.SetPermissionsAsync(new BlobContainerPermissions
{
PublicAccess =
BlobContainerPublicAccessType.Blob
});

}

//reading file name & file extention
file_extension = Path.GetExtension(fileToUpload);
filename_withExtension = Path.GetFileName(fileToUpload);

CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(filename_withExtension);
var dir = container.GetDirectoryReference("Temp");
cloudBlockBlob.Properties.ContentType = file_extension;

cloudBlockBlob.UploadFromStreamAsync(file); // << Uploading the file to the blob >>

Console.WriteLine("Upload Completed!");


}
}

现在使用以下代码调用upload_ToBlob方法:

AzureBlobSample azureBlob = new AzureBlobSample();

string rootdir = @"C:\Temp\Test\Version2\";

string[] files = Directory.GetFiles(rootdir);

foreach (string file in files)
{
azureBlob.upload_ToBlob(file, "rithwik");
}

输出:

enter image description here

关于c# - azure 函数将多个文件上传到 blob 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75010976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com