|
1 | 1 | import logging |
2 | 2 | import re |
| 3 | +import base64 |
3 | 4 | from http import HTTPStatus |
4 | 5 | from typing import List, Optional |
5 | 6 | from urllib.parse import urlparse, urlunparse, unquote, quote |
@@ -149,7 +150,16 @@ async def process_files( |
149 | 150 | @file_management_config_router.get("/download/{object_name:path}") |
150 | 151 | async def get_storage_file( |
151 | 152 | object_name: str = PathParam(..., description="File object name"), |
152 | | - download: str = Query("ignore", description="How to get the file"), |
| 153 | + download: str = Query( |
| 154 | + "ignore", |
| 155 | + description=( |
| 156 | + "How to get the file: " |
| 157 | + "'ignore' (default, return file info), " |
| 158 | + "'stream' (return file stream), " |
| 159 | + "'redirect' (redirect to download URL), " |
| 160 | + "'base64' (return base64-encoded content for images)." |
| 161 | + ), |
| 162 | + ), |
153 | 163 | expires: int = Query(3600, description="URL validity period (seconds)"), |
154 | 164 | filename: Optional[str] = Query(None, description="Original filename for download (optional)") |
155 | 165 | ): |
@@ -192,6 +202,28 @@ async def get_storage_file( |
192 | 202 | "ETag": f'"{object_name}"', |
193 | 203 | } |
194 | 204 | ) |
| 205 | + elif download == "base64": |
| 206 | + # Return base64 encoded file content (primarily for images) |
| 207 | + file_stream, content_type = await get_file_stream_impl(object_name=object_name) |
| 208 | + try: |
| 209 | + data = file_stream.read() |
| 210 | + except Exception as exc: |
| 211 | + logger.error("Failed to read file stream for base64: %s", str(exc)) |
| 212 | + raise HTTPException( |
| 213 | + status_code=HTTPStatus.INTERNAL_SERVER_ERROR, |
| 214 | + detail="Failed to read file content for base64 encoding", |
| 215 | + ) |
| 216 | + |
| 217 | + base64_content = base64.b64encode(data).decode("utf-8") |
| 218 | + return JSONResponse( |
| 219 | + status_code=HTTPStatus.OK, |
| 220 | + content={ |
| 221 | + "success": True, |
| 222 | + "base64": base64_content, |
| 223 | + "content_type": content_type, |
| 224 | + "object_name": object_name, |
| 225 | + }, |
| 226 | + ) |
195 | 227 | else: |
196 | 228 | # return file metadata |
197 | 229 | return await get_file_url_impl(object_name=object_name, expires=expires) |
|
0 commit comments