53

I want to do an HTTP POST of the contents (as a string) of a local file located at path/to/my-file.txt to a URL endpoint at http://example.com/.

For example, I might want to do the following:

  1. Extract the contents of the file my-file.txt as a string.
  2. URL encode the string.
  3. Store the encoded string as a variable named foo.

Then do something like this:

curl -d "data=foo" http://example.com/

(I don't actually need the foo variable. It's just a convenient way to describe my question.)

What are the commands I would need to execute this? Do I need to write a shell script? If so, how might it look?

Mowzer
  • 2,509

3 Answers3

59

According to the last section of -d in man curl:

If you start the data with the letter @, the rest should be a file name to read the data from, or - if you want curl to read the data from stdin. Multiple files can also be specified. Posting data from a file named foobar would thus be done with --data @foobar. When --data is told to read from a file like that, carriage returns and newlines will be stripped out.

That is you don't have to do anything fancy just prepend your filename with a @.

Lii
  • 215
  • 2
  • 13
user556625
  • 4,400
43

As mentioned in this related question if you want the file uploaded without any changes (curl defaults to stripping carriage-return/line-feed characters) then you may want to use the --data-binary option:

curl -X POST --data-binary @path/to/my-file.txt http://example.com/
Pierz
  • 2,169
29

To be explicitly clear, the accepted answer suggests:

curl -d "data=@path/to/my-file.txt" http://example.com/

The manual reference is here.

Also see this SE answer and this one also for multi-parts.

Yonatan
  • 113
Mowzer
  • 2,509