在分布式存储和大数据应用中,断点续传是一个重要的功能,它允许大文件上传在中断后可以从中断点恢复,而不是重新上传整个文件。本文将介绍如何使用Python封装MinIO的断点续传方法,并使用FastAPI创建一个API接口,最后使用Axios调用该接口。
首先,我们需要安装minio和fastapi库。
1 |
pip install minio fastapi uvicorn |
我们将创建一个Python函数,用于处理文件的断点续传。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from minio import Minio from minio.error import S3Error
def minio_client(): return Minio( "play.min.io", access_key="your-access-key", secret_key="your-secret-key", secure=True )
def upload_file_with_resume(client, bucket_name, object_name, file_path, part_size=10*1024*1024): upload_id = client.initiate_multipart_upload(bucket_name, object_name) try: with open(file_path, "rb") as file_data: part_number = 1 while True: data = file_data.read(part_size) if not data: break client.put_object(bucket_name, f"{object_name}.{part_number}", data, len(data), part_number=part_number, upload_id=upload_id) part_number += 1 client.complete_multipart_upload(bucket_name, object_name, upload_id) except S3Error as exc: client.abort_multipart_upload(bucket_name, object_name, upload_id) raise exc |
代码解释:
接下来,我们将使用FastAPI创建一个API接口,用于接收文件并调用我们的断点续传函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
from fastapi import FastAPI, File, UploadFile from fastapi.responses import JSONResponse
app = FastAPI()
@app.post("/upload/") async def upload_file(file: UploadFile = File(...)): try: client = minio_client() upload_file_with_resume(client, "my-bucketname", file.filename, file.file._file.name) return JSONResponse(status_code=200, content={"message": "File uploaded successfully"}) except Exception as e: return JSONResponse(status_code=500, content={"error": str(e)}) |
代码解释:
在客户端,我们将使用Axios来调用FastAPI创建的接口。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
async function uploadFileToMinIO(file) { const formData = new FormData(); formData.append('file', file);
try { const response = await axios.post('http://localhost:8000/upload/', formData, { headers: { 'Content-Type': 'multipart/form-data' } }); console.log(response.data); } catch (error) { console.error('Error uploading file:', error); } }
// 调用函数上传文件 const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; await uploadFileToMinIO(file); }); |
代码解释:
本文介绍了如何使用Python和FastAPI实现MinIO的断点续传功能,并使用Axios调用API接口。通过封装MinIO的分块上传逻辑,我们可以有效地处理大文件上传,并在上传过程中断后从中断点恢复。FastAPI提供了一个简洁的API接口,而Axios则方便地从客户端发起请求。这种方法为处理大规模数据提供了强大的支持,使得MinIO成为数据密集型应用的理想选择。