使用requests-toolbelt库时,在声明 upload_file 字段时,请务必指定文件名和 Content-Type 标头。下面是一个示例:
filename = 'my_file.txt' m = MultipartEncoder(fields={'upload_file': (filename, open(filename, 'rb'))}) r = requests.post( url, data=m, headers={'Content-Type': m.content_type}, verify=False, ) print(r.request.headers) # confirm that the 'Content-Type' header has been set.
另一个选择是使用 Python 的 requests 或 HTTPX 库,它们都可以有效地处理流式文件上传。以下是每个示例:
使用请求:
import requests url = '...' filename = '...' with open(filename, 'rb') as file: r = requests.post( url, files={'upload_file': file}, headers={'Content-Type': 'multipart/form-data'}, )
自动使用 HTTPX:
import httpx url = '...' filename = '...' with open(filename, 'rb') as file: r = httpx.post( url, files={'upload_file': file}, )
HTTPX 自动支持流式文件上传,而请求则需要设置Content-Type header为'multipart/form-data'。
FastAPI 的 .stream() 方法允许您通过将请求正文作为流访问来避免将大文件加载到内存中。要使用此方法,请按照下列步骤操作:
确保上传文件大小符合不超过指定的限制,可以使用 MaxSizeValidator。这是一个示例:
from streaming_form_data import streaming_form_data from streaming_form_data import MaxSizeValidator FILE_SIZE_LIMIT = 1024 * 1024 * 1024 # 1 GB def validate_file_size(chunk: bytes): if FILE_SIZE_LIMIT > 0: streaming_form_data.validators.MaxSizeValidator( FILE_SIZE_LIMIT). __call__(chunk)
这是一个包含这些技术的示例端点:
from fastapi import FastAPI, File, Request from fastapi.responses import HTMLResponse from streaming_form_data.targets import FileTarget, ValueTarget from streaming_form_data import StreamingFormDataParser app = FastAPI() @app.post('/upload') async def upload(request: Request): # Parse the HTTP headers to retrieve the boundary string. parser = StreamingFormDataParser(headers=request.headers) # Register FileTarget and ValueTarget objects. file_ = FileTarget() data = ValueTarget() parser.register('upload_file', file_) parser.register('data', data) async for chunk in request.stream(): parser.data_received(chunk) # Validate file size (if necessary) validate_file_size(file_.content) # Process the uploaded file and data. return {'message': 'File uploaded successfully!'}
以上是如何高效上传大文件(≥3GB)到FastAPI后端?的详细内容。更多信息请关注PHP中文网其他相关文章!