使用Python和FastAPI实现MinIO断点续传功能

在分布式存储和大数据应用中,断点续传是一个重要的功能,它允许大文件上传在中断后可以从中断点恢复,而不是重新上传整个文件。本文将介绍如何使用Python封装MinIO的断点续传方法,并使用FastAPI创建一个API接口,最后使用Axios调用该接口。

步骤1:安装必要的Python库

首先,我们需要安装miniofastapi库。

pip install minio fastapi uvicorn

步骤2:封装MinIO断点续传方法

我们将创建一个Python函数,用于处理文件的断点续传。

python 复制代码
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

代码解释:

  • minio_client函数创建并返回一个MinIO客户端实例。
  • upload_file_with_resume函数接受文件路径和存储桶信息,使用MinIO客户端进行分块上传。
  • 如果上传过程中发生错误,将终止上传并抛出异常。

步骤3:使用FastAPI创建API接口

接下来,我们将使用FastAPI创建一个API接口,用于接收文件并调用我们的断点续传函数。

python 复制代码
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)})

代码解释:

  • FastAPI应用创建了一个/upload/路由,接受POST请求。
  • file: UploadFile = File(...)参数表示我们期望接收一个文件。
  • upload_file_with_resume函数被调用来处理上传。
  • 如果上传成功,返回成功消息;如果失败,返回错误信息。

步骤4:使用Axios调用FastAPI接口

在客户端,我们将使用Axios来调用FastAPI创建的接口。

javascript 复制代码
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);
});

代码解释:

  • 我们创建了一个uploadFileToMinIO函数,它使用Axios发送POST请求到FastAPI服务器。
  • FormData对象用于构建包含文件数据的请求体。
  • 如果上传成功,打印响应数据;如果失败,打印错误信息。

注意事项

  1. 安全性:确保在生产环境中使用HTTPS,并正确配置访问密钥和秘密密钥。
  2. 错误处理:增强错误处理逻辑,以优雅地处理各种异常情况。
  3. 性能优化:根据实际需求调整分块大小,以优化上传性能。

总结

本文介绍了如何使用Python和FastAPI实现MinIO的断点续传功能,并使用Axios调用API接口。通过封装MinIO的分块上传逻辑,我们可以有效地处理大文件上传,并在上传过程中断后从中断点恢复。FastAPI提供了一个简洁的API接口,而Axios则方便地从客户端发起请求。这种方法为处理大规模数据提供了强大的支持,使得MinIO成为数据密集型应用的理想选择。

相关推荐
m0_74823364几秒前
RabbitMQ 进阶
android·前端·后端
m0_7482386310 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
菜鸟阿达1 小时前
spring boot 2.7 + seata +微服务 降级失败问题修复
spring boot·后端·微服务
清河__1 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang
张声录11 小时前
国密算法Sm2工具类--golang实现版
开发语言·后端·golang
一小路一10 小时前
从0-1学习Mysql第五章: 索引与优化
数据库·后端·学习·mysql·面试
mah66610 小时前
SpringBoot项目连接Oracle视图报错整理
spring boot·后端·oracle
IT学长编程11 小时前
计算机毕业设计 基于SpringBoot的智慧社区管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·后端·毕业设计·课程设计·论文笔记·1024程序员节
Asthenia041211 小时前
详细分析 `@@` 和 `${}` 的来源及启动配置
后端
奋斗的小方11 小时前
Springboot基础篇(3):Bean管理
java·spring boot·后端