tkuchikiの日記

新ブログ https://blog.tkuchiki.net

curl でファイルをPOST送信する方法とエラーの対処法

curlでファイルを送ろうとしたら少しハマったので、メモ。

curl コマンドでファイルを送る方法は、manを見ると以下のようになっている。

-F/--form <name=content>
              (HTTP) This lets curl emulate a filled-in form in which a user has pressed the sub-
              mit button. This causes curl to POST data using  the  Content-Type  multipart/form-
              data  according  to  RFC 2388. This enables uploading of binary files etc. To force
              the 'content' part to be a file, prefix the file name with an @ sign. To  just  get
              the  content  part from a file, prefix the file name with the symbol <. The differ-
              ence between @ and < is then that @ makes a file get attached in the post as a file
              upload,  while  the  <  makes  a text field and just get the contents for that text
              field from a file.

              Example, to send your password file to the server, where 'password' is the name  of
              the form-field to which /etc/passwd will be the input:

              curl -F password=@/etc/passwd www.mypasswords.com

              To  read content from stdin instead of a file, use - as the filename. This goes for
              both @ and < constructs.

              You can also tell curl what Content-Type to use by using 'type=', in a manner simi-
              lar to:

              curl -F "web=@index.html;type=text/html" url.com

              or

              curl -F "name=daniel;type=text/foo" url.com

              You  can  also  explicitly  change  the name field of a file upload part by setting
              filename=, like this:

              curl -F "file=@localfile;filename=nameinpost" url.com

              See further examples and details in the MANUAL.

              This option can be used multiple times.

  • F @ファイル名 (+content type) でいける。

以下のように、-F と -d を混合で使うと以下の様なエラーがでる。

$ curl -d foo=bar -F file=@index.html http://localhost
Warning: You can only select one HTTP request!

その場合は、-F で統一すればOK。