curl是开源的http上传和下载工具,通过命令行实现http操作,也可以使用其源码进行http编程,就不用重新实现http协议的接口了。
网上有很多curl使用的命令行示例和基于其接口开发的示例,这里我介绍一下使用curl上传文件的命令行。上传文件使用的是POST,multipart/form-data形式,命令行示例:
curl -F "file=@/home/xz/test.tar.gz;type=application/octet-stream" -F "usr=abc" -F "pwd=123" http://sifangyun.cn/upload_file.php
这里解释一下,-F选项可以有多个,不仅包含file类型,还能包含text,password等其他类型,但不能合并到一个-F选项,而要有多个-F选项。这个本质上是等价于html中form的字段,与上面命令对应的form可以写成下面这样:
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<label for="usr">Username:</label>
<input type="text" name="usr" id="usr" />
<br />
<label for="pwd">Password:</label>
<input type="password" name="pwd" id="pwd" />
<br />
<input type="submit" name="submit" value="上传" />
</form>
这里-F "file=@/home/xz/test.tar.gz;type=application/octet-stream"中的file是form中的字段name或id,type是MIME类型。
如果通过代理上传,则需要加上"-x yourproxy.com:port"的选项。
如果只上传参数,而不上传文件,则可以用application/x-www-url-encoded的方式发送POST请求,即在curl命令行里使用-d选项。形如:
curl -d "usr=abc" -d "pwd=123" http://sifangyun.cn/login.php
-d选项里是可以通过&来合并参数的,比如上面可以写成:
curl -d "usr=abc&pwd=123" http://sifangyun.cn/login.php