Azure Cloud Functions基于Python处理HTTP表单文件上传问题
Got it, let's tackle this file upload issue with your Azure Function HTTP trigger. When you upload a file via an HTML form, the request uses multipart/form-data encoding—that's why your raw body looks like unreadable binary data. We need to parse this format properly to extract the file content, and here's how to do it step by step:
1. 安装必要依赖
Azure Functions' Python runtime doesn't include a multipart/form-data parser by default, so we'll need to add the python-multipart package. Create a requirements.txt file in your function project root and add this line:
python-multipart>=0.0.6
When you deploy the function or run it locally, the environment will automatically install this dependency.
2. 解析请求体提取文件
There are two reliable ways to handle this—pick the one that fits your use case:
方式一:利用Flask原生请求解析(推荐)
Under the hood, Azure Functions' Python HTTP trigger uses Flask's request object, so we can directly use req.form and req.files to handle the upload:
import azure.functions as func def main(req: func.HttpRequest) -> func.HttpResponse: try: # Validate request content type content_type = req.headers.get('Content-Type', '') if 'multipart/form-data' not in content_type: return func.HttpResponse( "Please send requests with multipart/form-data encoding", status_code=400 ) # Get the uploaded file object (match the form field name here) uploaded_file = req.files.get('file') if not uploaded_file: return func.HttpResponse( "No file found in the request—check your form field name is 'file'", status_code=400 ) # Extract file details and content file_name = uploaded_file.filename file_content = uploaded_file.read() # Returns binary data # Add your business logic here (e.g., save to Azure Blob Storage) print(f"Received file: {file_name}, size: {len(file_content)} bytes") return func.HttpResponse( f"File {file_name} uploaded successfully!", status_code=200 ) except Exception as e: return func.HttpResponse( f"Error processing file: {str(e)}", status_code=500 )
方式二:手动解析原始二进制body(自定义场景)
If you prefer not to use external libraries, you can manually parse the multipart data using Python's built-in email module. This is more verbose but gives you full control:
import azure.functions as func import email from email.policy import default def main(req: func.HttpRequest) -> func.HttpResponse: try: content_type = req.headers.get('Content-Type', '') if 'multipart/form-data' not in content_type: return func.HttpResponse("Invalid content type", status_code=400) # Extract the boundary separator from the Content-Type header boundary = content_type.split('boundary=')[1].encode('utf-8') # Parse the raw body as an email message (multipart format is similar) msg = email.message_from_bytes(req.get_body(), policy=default) for part in msg.walk(): if part.is_multipart(): continue # Check if this part is a file attachment if part.get_filename(): file_name = part.get_filename() file_content = part.get_payload(decode=True) # Decode base64 if needed # Your custom processing logic here print(f"Uploaded file: {file_name}, content length: {len(file_content)}") return func.HttpResponse(f"File {file_name} uploaded successfully", status_code=200) return func.HttpResponse("No file found in request", status_code=400) except Exception as e: return func.HttpResponse(f"Error: {str(e)}", status_code=500)
3. 测试小提示
- Make sure your HTML form's file input field name matches the one in your code (e.g., if your form uses
<input type="file" name="upload">, changereq.files.get('file')toreq.files.get('upload')). - For local testing, use curl or Postman:
curl -X POST -F "file=@your-local-file.jpg" https://<your-function-url>/api/<function-name>
内容的提问来源于stack exchange,提问作者marco romelli

