如何在 Azure 函数中接收多部分表单数据?

Abh*_*eet 3 python azure-functions

我想在 Azure 函数中接收包含图像和文本的多部分数据。

我可以在 C# 和节点节点链接中看到很多示例,但在 python 中找不到任何东西。

在官方文档中也找不到任何内容Docs

Jay*_*SFT 8

我已经尝试了下面的代码,它对我有用:

import logging
import json
import io
from PIL import Image
from azure.storage.blob import BlobServiceClient,BlobClient
import azure.functions as func


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

    name = req.form['name']
    interests =json.dumps(req.form["interests"], indent=2)
    imagefile = req.files["file"]
    filename = imagefile.filename
    filestream = imagefile.stream
    filestream.seek(0)

    blob = BlobClient.from_connection_string(conn_str= "<your connection string>", container_name="<container name>", blob_name="<blob name>")

    blob.upload_blob(filestream.read(), blob_type="BlockBlob")

    if name:
        return func.HttpResponse(f"Hello, {name}. Created profile with your interests : {interests}. Uploaded your profile image file :{filename} to the blob. This function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,您也可以使用 PIL 从 image 中获取字节。然后代码看起来像:


import logging
import json
import io
from PIL import Image
from azure.storage.blob import BlobServiceClient,BlobClient
import azure.functions as func


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

    name = req.form['name']
    interests =json.dumps(req.form["interests"], indent=2)
    filename = req.files["file"].filename
    image = Image.open(req.files["file"])
    imgByteIO = io.BytesIO()
    image.save(imgByteIO, format=image.format)
    imgByteArr = imgByteIO.getvalue()

    blob = BlobClient.from_connection_string(conn_str= "<your connection string>", container_name="<container name>", blob_name="<blob name>")
    blob.upload_blob(imgByteArr)

    if name:
        return func.HttpResponse(f"Hello, {name}. Created profile with your interests : {interests}. Uploaded your profile image file :{filename} to the blob. This function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )


Run Code Online (Sandbox Code Playgroud)

这是邮递员的请求:

这是邮递员请求