You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提升WebDAV多文件及目录的上传速度?

WebDAV多文件上传速度优化问题

我正在开发一个基于WebDAV的上传脚本,已实现空目录创建及单个文件上传功能,但暂未找到批量上传整个目录或多文件的方法。因此,我只能逐个创建父目录并逐一上传文件,目录内文件越多,耗时越长——使用下方脚本上传100MB的Git项目需耗时约5分钟。

值得注意的是,少量大文件的上传速度远快于大量小文件。但遗憾的是,我无法在目标网站上解压文件,且多数WebDAV应用也不支持该操作,否则我只需上传tarball压缩包即可。

请问是否有办法提升WebDAV多文件上传的速度?

#!/usr/bin/env python
import os, sys, subprocess  
import webdav4.client

mycon = webdav4.client.Client("https://example.com", \
                        auth=("username", "password"))
dicti = {}

# Find directories within path
dicti["dirs"] = subprocess.run(\
        ('find', '-type', 'd', '-print0'),\
        capture_output=True, text=True).stdout.split('\0')

# Find files within path
dicti["files"] = subprocess.run(\
        ('find', '-type', 'f', '-print0'),\
        capture_output=True, text=True).stdout.split('\0')

for ky in ('dirs', 'files'):
    for i in dicti[ky]:
        if not mycon.exists('dest/' + i):
            if ky == "dirs":
                print(mycon.mkdir('dest/' + i))
            else:
                print(mycon.upload_file(i, 'dest/' + i))

优化方案
  • 并行上传文件:当前脚本串行处理每个文件,改成多线程并行上传可大幅提升小文件上传效率。用concurrent.futures.ThreadPoolExecutor实现,示例如下:

    from concurrent.futures import ThreadPoolExecutor
    
    def upload_single_file(local_path, remote_path):
        if not mycon.exists(remote_path):
            mycon.upload_file(local_path, remote_path)
            print(f"Uploaded {local_path}")
    
    # 过滤find命令拆分后产生的空字符串
    valid_files = [f for f in dicti["files"] if f]
    # 根据服务器承受能力调整max_workers数值
    with ThreadPoolExecutor(max_workers=10) as executor:
        for file_path in valid_files:
            remote_path = f'dest/{file_path}'
            executor.submit(upload_single_file, file_path, remote_path)
    
  • 批量递归创建目录:webdav4的mkdir方法支持parents=True参数,可一次性递归创建整个目录路径,无需逐个创建上级目录。优化后的目录处理逻辑:

    valid_dirs = [d for d in dicti["dirs"] if d]
    for dir_path in valid_dirs:
        remote_dir = f'dest/{dir_path}'
        if not mycon.exists(remote_dir):
            mycon.mkdir(remote_dir, parents=True)
            print(f"Created dir {remote_dir}")
    

    这能减少大量目录创建的HTTP请求次数。

  • 减少不必要的exists检查:如果是首次上传本地目录到远程,可直接跳过exists检查,直接执行创建目录和上传操作,省去每次请求前的额外校验请求。

  • 调整上传参数:检查webdav4的upload_file方法是否支持自定义分块大小,适当增大分块尺寸可减少小文件的请求次数;同时确保启用HTTP持久连接(webdav4基于requests库,默认已支持),避免每次请求重新建立TCP连接。

内容的提问来源于stack exchange,提问作者Maximilian Ballard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 12:55:22