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");
}
}
This is ok for uploading single file. What would be the best solution to provide multiple files upload using azure function.
CodePudding user response:
This function expects the request body to be an array of objects, each containing a name property (the name of the file) and a stream property (a readable stream containing the contents of the file). You can modify the function to suit your specific needs.
import { AzureFunction, Context, HttpRequest } from '@azure/functions';
import { BlobServiceClient, StorageSharedKeyCredential } from '@azure/storage-blob';
const httpTrigger: AzureFunction = async function(context: Context, req: HttpRequest): Promise<void> {
// Get the list of files from the request body
const files = req.body;
// Create a connection to Azure Blob Storage
const storageAccount = process.env.STORAGE_ACCOUNT;
const storageAccessKey = process.env.STORAGE_ACCESS_KEY;
const sharedKeyCredential = new StorageSharedKeyCredential(storageAccount, storageAccessKey);
const blobServiceClient = new BlobServiceClient(
`https://${storageAccount}.blob.core.windows.net`,
sharedKeyCredential
);
// Iterate over the list of files and store each one in Azure Blob Storage
for (const file of files) {
// Create a new blob in the specified container
const containerName = 'my-container';
const containerClient = blobServiceClient.getContainerClient(containerName);
const blockBlobClient = containerClient.getBlockBlobClient(file.name);
// Upload the contents of the file to the blob
const stream = file.stream;
await blockBlobClient.uploadStream(stream, file.size);
}
// Return a response to the client
context.res = {
status: 200,
body: 'Successfully uploaded files.'
};
};
export default httpTrigger;
CodePudding user response:
I have reproduced in my environment and got expected result below:
Firstly, I have 3 files in my folder as below:
upload_ToBlob Method:
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=";
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!");
}
}
Now call the upload_ToBlob method using below code:
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");
}
Output: