Skip to content Skip to sidebar Skip to footer

Result: Failure Exception: Typeerror: Argument Should Be A Bytes-like Object Or Ascii String, Not 'dict'

I'm having a problem with this homework where I'm sending a post request with an encoded image base64 as a json object in postman. I'm supposed to decode the json body and save it

Solution 1:

If you want to upload image file to Azure blob storage with Azure function, you can try to use the form to send your image to Azure function. For example

  1. add Storage connection string in local.settings.json
{"IsEncrypted":false,"Values":{"AzureWebJobsStorage":"","FUNCTIONS_WORKER_RUNTIME":"python","ConnectionString":"","ContainerName":""}}
  1. Code
import logging
import os
import azure.functions as func
from azure.storage.blob import BlobServiceClient, BlobClient
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        file=  req.files.get('the key value in your form')
        logging.info(file.filename)
        
        connect_str=os.environ["ConnectionString"]
        container=os.environ["ContainerName"]
        
        blob_service_client = BlobServiceClient.from_connection_string(connect_str)
        blob_client =blob_service_client.get_blob_client(container=container,blob=file.filename)
        blob_client.upload_blob(file)
    except Exception as ex:
        logging.info(ex.args)
       
    return func.HttpResponse("ok")
    
  1. Test in Postman enter image description hereenter image description hereenter image description here

Update

According to my test, if we use base64.b64decode() to decode, we will get bytes object. So we need to use create_blob_from_bytes to upload. For example

My code

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    # get image base64 string
    file=req.get_json()
    image=file['image'].replace(' ', '+')
    #decode base64 string
    data=base64.b64decode(image)
    logging.info(type(data))
    #upload
    block_blob_service = BlockBlobService(account_name='blobstorage0516', account_key='')
    container_name='test'
    blob_name='test.jpeg'
    block_blob_service.create_blob_from_bytes(container_name, blob_name, data)

  
    return func.HttpResponse(f"OK!")

enter image description hereenter image description here

Solution 2:

this is how I send the POST request and needs to be handle in my function app. I'm successfully able to create the blobs but I only get a broken image in the url from the blobs.enter image description here

Post a Comment for "Result: Failure Exception: Typeerror: Argument Should Be A Bytes-like Object Or Ascii String, Not 'dict'"