用python上传文件到百度网盘(使用百度网盘开放平台sdk)

 先上一张上传成功截图

运行代码如下 

# !/home/***/anaconda3/bin/python #选择合适的python版本
"""
    xpan upload
    include:
        precreate
        upload
        create
"""
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from pprint import pprint
from openapi_client.api import fileupload_api
import openapi_client
import hashlib

def precreate():
    """
    precreate
    """
    #    Enter a context with an instance of the API client
    with openapi_client.ApiClient() as api_client:
        # Create an instance of the API class
        api_instance = fileupload_api.FileuploadApi(api_client)
        access_token = "***"  #填入自己的access_token 
        path = "/apps/***/test.jpg"  # str | 对于一般的第三方软件应用,路径以 "/apps/your-app-name/" 开头。对于小度等硬件应用,路径一般 "/来自:小度设备/" 开头。对于定制化配置的硬件应用,根据配置情况进行填写。
        
        block_list =  ''
        file_path = "/***/test.jpg" #要上传的文件的真实路径
        with open(file_path, 'rb') as f:
            data = f.read()
            file_md5 = hashlib.md5(data).hexdigest() #获取上传文件md5
            block_list =  block_list+'["{}"]'.format(file_md5) #放入block_list
            print(block_list)

        size = os.path.getsize(file_path) #获取上传文件大小
        print(size)

        isdir = 0  # int | isdir 
        autoinit = 1  # int | autoinit
        rtype = 3  # int | rtype (optional)

        try:
            api_response = api_instance.xpanfileprecreate(
                access_token, path, isdir, size, autoinit, block_list, rtype=rtype)
            pprint(api_response)
            uploadid = api_response['uploadid'] #获取预上传返回的uploadid,传给upload和create函数
        except openapi_client.ApiException as e:
            print("Exception when calling FileuploadApi->xpanfileprecreate: %s\n" % e)
        return access_token, path, isdir, size, uploadid, block_list, rtype, file_path


def upload(uploadid,path,file_path, access_token):
    """
    upload
    """
    # Enter a context with an instance of the API client
    with openapi_client.ApiClient() as api_client:
        # Create an instance of the API class
        api_instance = fileupload_api.FileuploadApi(api_client)
        partseq = "0"  # str |
        type = "tmpfile"  # str |
        try:
            file = open(file_path, 'rb') 
        except Exception as e:
            print("Exception when open file: %s\n" % e)
            exit(-1)

        # example passing only required values which don't have defaults set
        # and optional values
        try:
            api_response = api_instance.pcssuperfile2(
                access_token, partseq, path, uploadid, type, file=file)
            pprint(api_response)
        except openapi_client.ApiException as e:
            print("Exception when calling FileuploadApi->pcssuperfile2: %s\n" % e)


def create(access_token, path, isdir, size, uploadid, block_list,rtype):
    """
    create
    """
    # Enter a context with an instance of the API client
    with openapi_client.ApiClient() as api_client:
        # Create an instance of the API class
        api_instance = fileupload_api.FileuploadApi(api_client)

        # example passing only required values which don't have defaults set
        # and optional values
        try:
            api_response = api_instance.xpanfilecreate(
                access_token, path, isdir, size, uploadid, block_list, rtype=rtype)
            pprint(api_response)
        except openapi_client.ApiException as e:
            print("Exception when calling FileuploadApi->xpanfilecreate: %s\n" % e)


if __name__ == '__main__':
    access_token, path, isdir, size, uploadid, block_list, rtype, file_path = precreate()
    upload(uploadid,path,file_path, access_token)
    create(access_token, path, isdir, size, uploadid, block_list,rtype)

把access_token,文件路径,上传路径修改为自己的,运行即可

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 好的,这是一个技术问题,我可以回答。下面是一个简单的Python类示例,可以用来上传本地文件到百度网盘: ```python import requests import json class BaiduNetdiskUploader: def __init__(self, access_token): self.access_token = access_token self.upload_url = 'https://pan.baidu.com/rest/2.0/xpan/file?method=upload&access_token=' + access_token def upload_file(self, file_path, save_path='/'): file_name = file_path.split('/')[-1] headers = {'User-Agent': 'Mozilla/5.0'} data = {'path': save_path + file_name} files = {'file': open(file_path, 'rb')} response = requests.post(self.upload_url, headers=headers, data=data, files=files) result = json.loads(response.text) if 'error_code' in result: print('Upload failed: ' + result['error_msg']) else: print('Upload success: ' + file_name) # 使用示例 access_token = 'your_baidu_netdisk_access_token' uploader = BaiduNetdiskUploader(access_token) uploader.upload_file('/path/to/your/local/file') ``` 在这个示例中,我们通过调用百度网盘的API,使用access_token进行身份验证,并上传本地文件到指定的目录。你需要将 `your_baidu_netdisk_access_token` 替换为你自己的百度网盘access_token,`/path/to/your/local/file` 替换为你想要上传的本地文件路径。 ### 回答2: 要使用Python编写一个类来实现将本地文件上传到百度网盘,可以按照以下步骤进行编写: 1. 首先需要导入必要的模块,例如bypy和os模块。bypy是百度云网盘的Python API接口库,可用于控制文件的上传和下载操作。 2. 创建一个类,例如BaiduNetDiskUploader,作为文件上传器。 3. 在类的构造函数中,可以初始化bypy的API对象,这需要输入百度云网盘的应用授权信息。 4. 可以定义一个上传文件的方法,例如upload_file方法,该方法需要传入本地文件的路径作为参数。在方法体内,可以使用os.path模块获取文件名和文件夹路径。 5. 在upload_file方法中,可以调用bypy的upload方法,将本地文件上传到百度网盘。upload方法需要传入两个参数,分别是文件路径和上传到百度网盘的目标路径。 下面是一个示例代码: ```python import os import bypy class BaiduNetDiskUploader: def __init__(self, app_key, app_secret): self.client = bypy.BaiduYun(app_key, app_secret) def upload_file(self, file_path): file_name = os.path.basename(file_path) target_path = "/path/to/upload/destination/" # 设置上传到百度云的目标路径 self.client.upload(file_path, target_path + file_name) # 示例用法 app_key = "your_app_key" app_secret = "your_app_secret" uploader = BaiduNetDiskUploader(app_key, app_secret) local_file_path = "/path/to/local/file.txt" uploader.upload_file(local_file_path) ``` 以上示例代码仅供参考,具体的百度云网盘授权信息、文件上传路径等需要根据实际情况进行修改。另外,还可以根据需要添加其他功能,例如下载文件、创建文件夹等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值