乐闻世界logo
搜索文章和话题

cURL 如何实现文件上传功能?

3月7日 19:37

文件上传是 cURL 的重要功能,支持多种上传方式,包括表单上传、二进制上传、多文件上传等。

基本文件上传

使用 -F--form 参数进行表单方式上传:

bash
# 上传单个文件 curl -X POST https://api.example.com/upload \ -F "file=@/path/to/file.pdf" # 指定 MIME 类型 curl -X POST https://api.example.com/upload \ -F "file=@/path/to/image.png;type=image/png" # 指定服务器接收的文件名 curl -X POST https://api.example.com/upload \ -F "file=@/path/to/local.txt;filename=uploaded.txt"

多文件上传

bash
# 上传多个文件 curl -X POST https://api.example.com/upload \ -F "file1=@/path/to/file1.pdf" \ -F "file2=@/path/to/file2.jpg" \ -F "file3=@/path/to/file3.txt" # 使用数组形式上传多个文件 curl -X POST https://api.example.com/upload \ -F "files[]=@/path/to/file1.pdf" \ -F "files[]=@/path/to/file2.jpg" # 混合文件和表单数据 curl -X POST https://api.example.com/submit \ -F "name=张三" \ -F "email=zhangsan@example.com" \ -F "avatar=@/path/to/avatar.jpg" \ -F "resume=@/path/to/resume.pdf"

二进制文件上传

bash
# 使用 --data-binary 上传原始二进制数据 curl -X POST https://api.example.com/upload \ -H "Content-Type: application/octet-stream" \ --data-binary @/path/to/file.bin # 从标准输入读取 cat file.bin | curl -X POST https://api.example.com/upload \ -H "Content-Type: application/octet-stream" \ --data-binary @- # 上传并显示进度 curl -X POST https://api.example.com/upload \ -F "file=@/path/to/large.zip" \ --progress-bar

Base64 编码上传

bash
# 将文件编码为 Base64 后上传 curl -X POST https://api.example.com/upload \ -H "Content-Type: application/json" \ -d "{\"file\":\"$(base64 -w 0 /path/to/file.pdf)\",\"filename\":\"document.pdf\"}"

分块上传(大文件)

bash
# 上传大文件并显示进度 curl -X POST https://api.example.com/upload \ -F "file=@/path/to/large_file.zip" \ -H "Authorization: Bearer token123" \ --progress-bar | tee upload.log # 断点续传(需要服务器支持) curl -C - -X POST https://api.example.com/upload \ -F "file=@/path/to/large_file.zip"

上传到云存储

bash
# AWS S3 上传 curl -X PUT "https://bucket.s3.amazonaws.com/file.pdf" \ -H "Content-Type: application/pdf" \ -H "Authorization: AWS4-HMAC-SHA256 ..." \ --data-binary @/path/to/file.pdf # 使用预签名 URL 上传 curl -X PUT "https://presigned-url-here" \ -H "Content-Type: application/pdf" \ --data-binary @/path/to/file.pdf

关键参数说明

参数作用示例
-F--form表单上传-F "file=@path"
@读取文件@/path/to/file
;type=指定 MIME 类型file=@img.png;type=image/png
;filename=指定文件名file=@local.txt;filename=remote.txt
--data-binary二进制上传--data-binary @file.bin
-C -断点续传-C -

完整上传示例

bash
# 带认证和元数据的完整上传 curl -X POST https://api.example.com/v1/files/upload \ -H "Authorization: Bearer your_token" \ -H "X-Upload-Category: documents" \ -F "file=@/path/to/document.pdf" \ -F "metadata={\"title\":\"合同文档\",\"tags\":[\"legal\",\"contract\"]};type=application/json" \ --progress-bar \ -o response.json # 查看上传结果 cat response.json | jq

常见问题解决

bash
# 问题 1:文件路径错误 # 解决:使用绝对路径或确认相对路径正确 # 问题 2:权限不足 # 解决:检查文件读取权限 ls -l /path/to/file # 问题 3:上传大小限制 # 解决:分块上传或联系服务器管理员 # 问题 4:超时 # 解决:增加超时时间 curl --max-time 600 -F "file=@large.zip" https://api.example.com/upload

标签:cURL