1. 概述
cURL 是一个用于发送网络请求的命令行工具,支持HTTP、HTTPS 和 FTP协议等协议。
本教程,我们将学习在curl中如何读取文件数据发送POST请求,以及如何实现上传文件功能。
2. curl从文件中读取数据
当使用 cURL 发送POST请求时,如果数据比较多,把请求参数直接写在命令行上不好看也不方便修改。我们可以考虑把数据保存到一个本地文件,curl会自动读取文件内容。
为了方便测试,这里推荐一个在线工具webhook.site,它会给你分配一个唯一API地址,当你请求的时候会记录整个请求详情,非常方便。
我的接口地址是:
server_endpoint="https://webhook.site/5610141b-bd31-4940-9a83-1db44ff2283e"
接下来,准备一个JSON文件。示例JSON文件,然后使用 –data
选项进行curl
请求:
$ curl --header "Content-Type: application/json" \
> --data "$(cat ~/Downloads/sample1.json)" \
> --trace-ascii trace-json-data-request.log \
> $server_endpoint
我们使用 –trace-ascii
跟踪 curl
请求,以便于验证请求。
除了使用 cat
命令,另一种方法是使用 @file
让 curl
读取文件内容:
$ curl --header "Content-Type: application/json" \
> --data "@~/Downloads/sample1.json" \
> --trace-ascii trace-json-data-request.log \
> $server_endpoint
最后,检查 trace-json-data-request.log
文件以确认数据已成功发送:
$ grep --max-count=1 --after-context=2 "Send data" trace-json-data-request.log
=> Send data, 65 bytes (0x41)
0000: {. "fruit": "Apple",. "size": "Large",. "color": "Red".
0040: }
看起来一切正常。
3. 文件上传
通过POST表单请求,我们可以发送文件数据。在 curl
中通过 –form
参数实现。
现在,下载一个示例GIF文件。下面我们发送文件和还有其他一些参数:
$ curl --form '[email protected];type=image/gif' \
--form 'username=baeldung' \
--form 'user_id=123' \
--trace-ascii trace-form-request.log
$server_endpoint
接下来,检查trace-form-request.log
文件,确认请求正确发送:
$ grep --max-count=3 \
--after-context=2 \
--before-context=1 \
-e 'username' -e 'user_id' -e 'gif' \
trace-form-request.log
006c: f"
0070: Content-Type: image/gif
0089:
008b: GIF89a.......................................................#..
--
6bb5: --------------------------b17d10ecc2112c14
6be1: Content-Disposition: form-data; name="username"
6c12:
6c14: baeldung
6c1e: --------------------------b17d10ecc2112c14
6c4a: Content-Disposition: form-data; name="user_id"
6c7a:
6c7c: 123
注意到curl
理解了image/gif
内容类型,并方便地将文件数据发送到服务器。此外,使用grep
命令的–before-context
和–after-context
选项,我们可以查看trace-form-request.log
文件中匹配行前后的内容。
最后,从webhook.site页面下载文件,确认服务器端接收到的数据:
可以看到,“Form values” 里面有我们发送的 username
和user_id
参数,上传的sample.gif
文件在Files一栏。
然而,这种方法不适用于非文本文件,如mp3、jpeg等。
4. 发送多个文件
在本节中,我们继续使用 curl
和 –form
发送多个文件。
下载两个示例MP3文件,然后使用–form
选项发送:
$ curl --form '[email protected];type=audio/mp3' \
--form '[email protected];type=audio/mp3' \
--trace-ascii trace-form-request-multi-files.log \
$server_endpoint
接着,检查trace-form-request-multi-files.log
文件,确认请求按预期发送:
$ grep --max-count=6 --after-context=2 --before-context=1 -e 'mp3' trace-form-request-multi-files.log
002c: Content-Disposition: form-data; name="file1"; filename="sample1.
006c: mp3"
0072: Content-Type: audio/mp3
008b:
008d: ID3......#TSSE.......Lavf57.83.100.............P................
--
d25f: Content-Disposition: form-data; name="file2"; filename="sample2.
d29f: mp3"
d2a5: Content-Type: audio/mp3
d2be:
=> Send data, 65536 bytes (0x10000)
看起来正确。
最后,访问webhook.site页面,确认服务器成功接收了所有文件:
我们可以看到,“Files” 一栏包含了 sample1.mp3
和 sample2.mp3
文件。
5. 总结
在这篇文章中,我们学习了使用cURL从文件发送数据。此外,我们了解了–data
和–form
选项的应用来解决不同的场景。