azure-functionsazure-blob-storage

Handling file upload in static web app with azure functions v4


i struggle with a simple file-upload to my static web app. Im using azure function v4 to handle incoming requests. normal requests and form-data is handled with a function like this ( body is JSON-String):

app.http('addItem', {
methods: ['POST'],
authLevel: 'anonymous',
handler: async (request, context) => {
    context.log(`Http function processed request for url "${request.url}"`);

    let itemJSON = await request.text();
/* do some stuff here */

But if i submit a file, i dont know how to access it from backend to e.g. upload the buffer / stream to azure blob storage. I tried "formData()" and "text()" and allways get some wired backend errors...

app.http( 'fileupload', {
methods: ['POST'],
authLevel: 'anonymous',
handler: async ( req, context ) => {

    let formData = await req.formData();
    /*let textData = await req.text();*/

There are more options to access the request: https://learn.microsoft.com/en-us/azure/azure-functions/functions-node-upgrade-v4?tabs=v4&pivots=programming-language-javascript#review-your-usage-of-http-types

but how do i get the file as blob or stream to pass it to my azure blob upload... I cant find any example using v4 functions and handle a file-upload. I see some older examples with multer (but i dont use express, so its bit complicated to implement it i belief).

Has anybody a hint for me how to correctly access the file (first its only single-file upload) and pass it to blob-storage without local saving? Like passing the request-stream / request-blob direct to azure-blob-storage-functions?

Thx a lot!


Solution

  • ok... I found a simple and easy way to achive this... Simple use the "uploadData" function from BlockBlobClient with an arrayBuffer from the uploaded file :)

    let formData = await req.formData();
    let file = formData.get( "file" );
    let buffer = file.arrayBuffer();
    await blockBlobClient.uploadData( buffer );
    

    So i can upload my files to azure blobstorage through a simple html file-form upload :)

    uploadData function:

    https://learn.microsoft.com/en-us/javascript/api/@azure/storage-blob/blockblobclient?view=azure-node-latest#@azure-storage-blob-blockblobclient-uploaddata