Azure Pub Sub是否支持图片与二进制文档传输?求Python实现示例及限制说明
Azure Pub Sub 发送二进制内容(图片/文档)指南
1. 传输能力说明
Azure Pub Sub并非仅支持文本传输,它原生支持二进制数据发送。你可以直接传递字节流形式的图片、文档等二进制内容,无需强制转换为文本;若需兼容文本协议场景,也可将二进制数据编码为Base64字符串后传输。
2. 相关限制
- 消息大小限制:单条二进制消息默认最大为1MB,部分服务层级可调整至10MB。超过限制的大文件需自行实现分片传输逻辑。
- 配额限制:每日消息发送量、并发连接数等受服务层级配额约束,需根据实际使用场景确认对应配额。
- 内容无格式限制:所有合法二进制数据(如JPG/PNG图片、PDF/Excel文档等)均可发送,服务不会解析内容本身。
3. Python 实现示例
依赖安装
首先安装Azure Pub Sub相关SDK:
pip install azure-webpubsub azure-core
示例1:直接发送二进制字节流
from azure.webpubsub import WebPubSubServiceClient from azure.core.credentials import AzureKeyCredential import os # 初始化客户端 connection_string = "<你的Azure Web PubSub连接字符串>" hub_name = "<你的Hub名称>" service_client = WebPubSubServiceClient.from_connection_string(connection_string, hub_name=hub_name) # 读取本地文件并发送二进制数据 def send_binary_file(file_path): with open(file_path, "rb") as f: binary_data = f.read() # 发送到指定群组 service_client.send_to_group( group_name="test-group", content=binary_data, content_type="application/octet-stream" ) print(f"文件 {file_path} 发送完成") # 调用示例 send_binary_file("test-image.jpg")
示例2:Base64编码后发送(兼容文本场景)
import base64 def send_base64_encoded_file(file_path): with open(file_path, "rb") as f: binary_data = f.read() # 编码为Base64字符串 base64_content = base64.b64encode(binary_data).decode("utf-8") service_client.send_to_group( group_name="test-group", content=base64_content, content_type="text/plain" ) print(f"Base64编码文件 {file_path} 发送完成") # 调用示例 send_base64_encoded_file("test-document.pdf")
接收端处理二进制消息
# 假设接收端获取到二进制消息内容 def save_binary_content(content, save_path): with open(save_path, "wb") as f: f.write(content) print(f"文件已保存至 {save_path}")
内容的提问来源于stack exchange,提问作者jonyp
相关产品推荐
相关产品推荐

