大文件上传服务器频繁失败?分卷压缩简单用法
引言:大文件上传的痛点
在开发运维场景中,上传数GB的大文件到服务器时,你是否遇到过这些问题?
-
网络波动导致传输中断需从头开始
-
服务器限制单文件大小(如HTTP请求体积限制)
-
传输过程中因意外断电/断网导致文件损坏
分卷压缩技术可将大文件拆分为多个小文件,有效规避上述问题。本文将手把手教你使用Linux命令实现分卷压缩、传输与校验。
一、分卷压缩实战步骤
1.1 压缩文件(若未压缩)
# 将目录打包为.tar.gz格式(兼顾压缩率与通用性) tar czvf thechat-image.tar.gz thechat-image/
参数说明:
-
c
:创建压缩包 -
z
:启用gzip压缩 -
v
:显示进度 -
f
:指定文件名
1.2 分卷压缩(50M/卷)
split -b 50M thechat-image.tar.gz "thechat-image.tar.gz.part"
生成文件示例:
thechat-image.tar.gz.partaa thechat-image.tar.gz.partab thechat-image.tar.gz.partac ...
高级配置:
# 使用数字后缀(生成.part00/.part01) split -d -b 50M thechat-image.tar.gz "thechat-image.tar.gz.part" # 自定义后缀长度(3位数字,如.part001) split -a 3 -d -b 50M thechat-image.tar.gz "thechat-image.tar.gz.part"
1.3 合并与解压(接收端操作)
# 合并所有分卷(注意按字母顺序排列) cat thechat-image.tar.gz.part* > restored.tar.gz # 解压文件(推荐管道直接解压,避免磁盘写两次) cat thechat-image.tar.gz.part* | tar xzv
二、分卷文件上传服务器
2.1 推荐方法:通配符批量上传
# 上传所有.part*文件到服务器 scp thechat-image.tar.gz.part* user@remote_host:/target_path/ # 使用rsync(支持断点续传) rsync -avzP thechat-image.tar.gz.part* user@remote_host:/target_path/
2.2 精确匹配特定范围
# 上传partaa到partbb(生成aa/ab/ba/bb组合) scp thechat-image.tar.gz.part{a{a..b},b{a..b}} user@remote_host:/target_path/
三、确保文件完整性:SHA256校验
3.1 生成校验文件
# 为所有分卷生成哈希(推荐) sha256sum thechat-image.tar.gz.part* > checksum.sha256 # 合并后单独校验 sha256sum restored.tar.gz > full_checksum.sha256
3.2 校验文件
# 校验分卷文件 sha256sum -c checksum.sha256 # 校验合并后的文件 sha256sum -c full_checksum.sha256
四、注意事项与技巧
-
文件顺序保障 Linux默认按字母序合并文件,建议:
-
使用数字后缀(
-d
参数) -
避免手动重命名分卷文件
-
-
权限与路径
-
提前创建服务器目录:
ssh user@host "mkdir -p /target_path"
-
配置SSH密钥认证避免重复输密码:
ssh-keygen ssh-copy-id user@remote_host
-
-
跨平台兼容
-
Windows用户可使用Git Bash执行命令
-
macOS需安装
coreutils
以支持完整参数
-
五、为什么选择分卷压缩?
方案 | 断点续传 | 文件校验 | 跨平台兼容 | 实施复杂度 |
---|---|---|---|---|
分卷压缩 | ✅ | ✅ | ✅ | ⭐️⭐️ |
FTP工具 | ✅ | ❌ | ❌ | ⭐️⭐️⭐️ |
云存储分片上传 | ✅ | ✅ | ✅ | ⭐️⭐️⭐️⭐️ |
压缩包直传 | ❌ | ✅ | ✅ | ⭐️ |
分卷压缩优势:
-
无需安装额外工具(纯系统命令)
-
可组合使用(如分卷+加密)
-
天然支持断点续传(重传单个分卷)
结语
通过分卷压缩技术,我们成功将大文件拆分为多个小文件上传,结合哈希校验确保数据完整性。该方法尤其适合以下场景:
-
通过不稳定网络传输重要数据
-
绕过服务器的文件大小限制
-
需要长期存储备份的归档文件
立即尝试文中命令,告别大文件上传失败困扰!