Home > Blockchain >  Elaborate and store inside an azure blob multiple files from a form-data request by using azure func
Elaborate and store inside an azure blob multiple files from a form-data request by using azure func

Time:11-12

I am developing an azure function that receives in input several files of different formats (eg xlsx, csv, txt, pdf, png) through the form-data format. The idea is to develop a function that can take files and store them one by one inside a blob. At the moment, my code is as follows:

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    filename, contents = False, False
    try:
        files = req.files.values()
        for file in files: 
            filename = str(file.filename)
            logging.info(type(file.stream.read()))
            contents = file.stream.read().decode('utf-8')
     except Exception as ex:
        logging.error(str(type(ex))   ': '   str(ex))
        return func.HttpResponse(body=str(ex), status_code=400)

Then i write the content variable inside the blob but the files inside the blob had 0 as size and if i try to download the file, the files are empty. How can i manage this operation to store different format files inside a blob? Thanks a lot for your support!

CodePudding user response:

Below is the code to upload multiple files of different formats:

from  azure.storage.blob  import  BlobServiceClient, BlobClient, ContainerClient,PublicAccess
import  os

def  UploadFiles():
CONNECTION_STRING="ENTER_STORAGE_CONNECTION_STRING"
Container_name="uploadcontainer"
service_client=BlobServiceClient.from_connection_string(CONNECTION_STRING)
container_client = service_client.get_container_client(Container_name)
ReplacePath = "C:\\"
local_path = "C:\Testupload"  #the local folder

for  r,d,f  in  os.walk(local_path):
    if  f:
    for  file  in  f:
    AzurePath = os.path.join(r,file).replace(ReplacePath,"")
    LocalPath = os.path.join(r,file)
    blob_client = container_client.get_blob_client(AzurePath)
    with  open(LocalPath,'rb') as  data:
    blob_client.upload_blob(data)
    
if  __name__ == '__main__':
    UploadFiles()
    print("Files Copied")

As from your question I am not able to get how your function is getting triggered, and where you are uploading your files. So as per your logic you can use the above piece of code to upload all type of files.

Currently above code can be used to upload all the files in a local folder. Below is the screenshot for a repro:

enter image description here

  • Related