利用python代码上传文件到七牛云
代码功能:① 读取七牛云Bucket文件列表。② 上传示例图片到七牛云Bucket中的指定存储路径。
你需要修改的参数:key(access key)、secret(secret key)、bucket_name、localfile(本地测试文件路径)、image_file中的测试域名。
# -*- coding: utf-8 -*-
# RUN TIME: Python 3.10
# CREATION ON: 2022-04-03(周日) 09:40:41
from qiniu import Auth, BucketManager, put_file
# 七牛相关配置
host = "rs.qbox.me" # 不用修改
key = "" # access key
secret = "" # secret key
q = Auth(key, secret)
bucket = BucketManager(q)
bucket_name = "" # 填你自己桶名称
def get_file_list():
bucket = BucketManager(q)
# 前缀
prefix = "img" # 填写存储桶的目标文件夹
# 列举条目
limit = 1000
# 列举出除'/'的所有文件以及以'/'为分隔的所有前缀
delimiter = None
# 标记
marker = None
ret, eof, info = bucket.list(bucket_name, prefix, marker, limit, delimiter)
# print(info)
items: list = ret.get('items')
# 所有百分号(%25)都被转义为了百分号(%), 将 25 补充回去
keys = []
for item in items:
key = item.get('key')
idx = key.find('%')
if idx >= 0:
key = f'{key[:idx+1]}25{key[idx+1:]}'
keys.append(key)
print(keys)
def put_img():
# 上传后保存的文件名
key = '3-sigma-all.jpg'
# 生成上传token
token = q.upload_token(bucket_name, key)
# 要上传文件的路径
localfile = '3-sigma-all.png' # 测试文件
ret, _ = put_file(token, key, localfile)
# 拼接路径:r9ev3tkv2.bkt.clouddn.com 是创建空间时分配的测试域名,img是Bucket下自己创建的文件夹名称
image_file = 'http://r9ev3tkv2.bkt.clouddn.com/img/' + ret.get('key')
print(image_file)
if __name__ == '__main__':
print("file list in the bucket:")
get_file_list()
put_img()