在設計API時有上傳檔案的需求,上傳檔案必須用POST送,不能用GET... 怎麼辦呢?
Server 假設用php收資料,get_request.php:
echo "\$_REQUEST:"; print_r($_REQUEST); echo "\$_FILES:"; print_r($_FILES); echo "\$_POST:"; print_r($_POST); echo "\$_GET:"; print_r($_GET);
使用Linux的curl:
GET:
$ curl "http://localhost/get_request.php?b=1"
結果:
$_REQUEST:Array
(
[b] => 1
)
$_FILES:Array
(
)
$_POST:Array
(
)
$_GET:Array
(
[b] => 1
)
POST:
$ curl --data "a=2&b=3" "http://localhost/get_request.php"
結果:
$_REQUEST:Array
(
[a] => 2
[b] => 3
)
$_FILES:Array
(
)
$_POST:Array
(
[a] => 2
[b] => 3
)
$_GET:Array
(
)
https連結
http://stackoverflow.com/questions/10079707/https-connection-using-curl-from-command-line
$ curl -k "https://whatever.com/script.php"
上傳檔案:
$ curl -F "file=@chrome.jpg;filename=nameinpost" -F "a=2" http://localhost/get_request.php?b=1
結果:
$_REQUEST:Array
(
[b] => 1
[a] => 2
)
$_FILES:Array
(
[file] => Array
(
[name] => nameinpost
[type] => image/jpeg
[tmp_name] => /tmp/phpNKmLsv
[error] => 0
[size] => 4164
)
)
$_POST:Array
(
[a] => 2
)
$_GET:Array
(
[b] => 1
)
註:
-F 指定檔案, 之後要post資料一樣要-F ,"file=@chrome.jpg;filename=nameinpost",filename= 可以指定新的上傳檔案名稱
ps. 如果遇到server有做 HTTP authentication ,用curl如何認證?
$ curl http://user:password@example.org/
或
$ curl -u user:password http://example.org/
使用php的curl函數,curl.php:
$toURL = "http://localhost/get_request.php?b=1"; $post = array( "a"=>"2", "userfile"=>"@chrome.jpg", //檔案若和程式在同一目錄或相對目錄, 可以用getcwd(), 如: // "userfile"=>"@".getcwd()."/oxox.doc", // 另外還可以在檔名後面加上分號指定mimetype(較新版的PHP才能使用) // (預設的 mimetype 為application/octet-stream) // "userfile"=>"@".getcwd()."\\somePic.png;type=image/png" ); $ch = curl_init(); $options = array( CURLOPT_URL=>$toURL, CURLOPT_POST=>true, CURLOPT_POSTFIELDS=>$post, // 直接給array ); curl_setopt_array($ch, $options); curl_exec($ch); curl_close($ch);$ php curl.php
結果:
$_REQUEST:Array
(
[bear] => 2
[a] => 123
)
$_FILES:Array
(
[userfile] => Array
(
[name] => chrome.jpg
[type] => application/octet-stream
[tmp_name] => /tmp/phpilTGG5
[error] => 0
[size] => 4164
)
)
$_POST:Array
(
[a] => 123
)
$_GET:Array
(
[bear] => 2
)
參考資料:
http://stackoverflow.com/questions/14978411/http-post-and-get-using-curl-in-linux
http://evelynnote.blogspot.sg/2011/03/curl.html 更多的curl 指令用法
http://blog.roodo.com/esabear/archives/16358749.html
沒有留言:
張貼留言