AWS预签名URL的数据上传进度跟踪器
创始人
2024-09-28 01:00:55
0次

以下是一个使用Python语言的示例代码,用于跟踪AWS预签名URL的数据上传进度。

import requests
import os
import boto3
import threading

class ProgressPercentage(object):
    def __init__(self, filename):
        self._filename = filename
        self._size = float(os.path.getsize(filename))
        self._lock = threading.Lock()
        self._uploaded = 0

    def __call__(self, bytes_amount):
        with self._lock:
            self._uploaded += bytes_amount
            percentage = (self._uploaded / self._size) * 100
            print(f"Uploaded {self._uploaded} bytes out of {self._size} ({percentage:.2f}%)")

# 获取预签名URL
def get_presigned_url(bucket, key):
    s3_client = boto3.client('s3')
    response = s3_client.generate_presigned_url(
        'put_object',
        Params={
            'Bucket': bucket,
            'Key': key,
        },
        ExpiresIn=3600 # URL有效期为1小时
    )
    return response

# 使用预签名URL上传文件
def upload_file_with_progress(url, file_path):
    with open(file_path, 'rb') as file:
        total_size = os.path.getsize(file_path)
        headers = {'Content-Length': str(total_size)}
        response = requests.put(url, data=file, headers=headers, stream=True)
        if response.status_code == 200:
            print("File uploaded successfully")
        else:
            print("File upload failed")

# 示例用法
def main():
    bucket = 'your-bucket-name'
    key = 'your-file-key'
    file_path = 'path/to/your/file'

    url = get_presigned_url(bucket, key)
    progress = ProgressPercentage(file_path)

    upload_thread = threading.Thread(
        target=upload_file_with_progress,
        args=(url, file_path),
        kwargs={'progress_callback': progress}
    )
    upload_thread.start()

    # 等待上传完成
    upload_thread.join()

if __name__ == '__main__':
    main()

上述代码中,我们定义了一个ProgressPercentage类,用于跟踪上传进度。在每次上传数据时,会调用该类的__call__方法来更新进度信息。

get_presigned_url函数使用AWS SDK的generate_presigned_url方法来获取预签名URL。upload_file_with_progress函数使用requests库发送PUT请求来上传文件,并将进度信息传递给ProgressPercentage类。

在主函数main中,我们可以设置bucket、key和file_path来指定要上传的文件。然后,我们获取预签名URL并创建一个ProgressPercentage对象。接下来,我们创建一个线程来执行文件上传操作,并在最后等待上传完成。

请确保已安装所需的Python库(boto3和requests),并将示例代码中的your-bucket-name、your-file-key和path/to/your/file替换为实际的值。

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...