8

I am trying to send a base64 encoded image from the command line using curl and base64 like this:

curl -X POST -H "Content-Type: application/json" -d '{"image" : $( base64 ~/Pictures/1.jpg )}' http://some/url/  

However, I get a response back saying that $ is an unexpected token. How do I send the base64 encoded image?

18

@muru is correct, however if you are trying to send a json encoding your base64 data may be too large for the command line and you may prefer something like this:

(echo -n '{"image": "'; base64 ~/Pictures/1.jpg; echo '"}') |
curl -H "Content-Type: application/json" -d @-  http://some/url/ 

The -X POST is implied by -d.

  • Yes, this much better. – muru Jul 20 '15 at 10:37
  • Hi meuh, I failed when I try to run this combined command line from PHP code, $html = shell_exec($str); if I copy $str code and run directly in command line, it's fine. But shell_exec did not work, please help :( thank you so much. – Bảo Nam Mar 30 '18 at 18:19
  • Haha, I created bash file, chmod +x that file, then write my command to file and run shell_exec('/path to sh file/xxx.sh');, I worked like a charm. Thanks. – Bảo Nam Mar 30 '18 at 18:35
  • 1
    @BảoNam Ok, good solution. I don't much about php, and I don't see any obvious reason why the first version did not work. Look in the error log file of your server for clues. You would be better off starting a new question when php is involved, I think. – meuh Mar 30 '18 at 18:39
5

Bash doesn't expand in single quotes. '{"image" : $( base64 ~/Pictures/1.jpg )}' gets sent as-is. Instead, try:

'{"image" : "'"$( base64 ~/Pictures/1.jpg)"'"}'

(Exit the opening quote before doing command substitution then open a quote again.)

  • 2
    You need to double-quote the $() else the base64 output lines will be split into several curl arguments. – meuh Jul 20 '15 at 10:33
  • Multiple images files and data command $ curl -d "name=Avatar&username=avatar&password=A1234567&email=avatar@user.com&token=16b185fe421d5017afb11691681906ed" --data-urlencode 'avatar='"$( base64 ~/Pictures/avatar004.jpg)"'' --data-urlencode 'image='"$( base64 ~/Pictures/avatar001.jpg)"'' --data-urlencode 'picture='"$( base64 ~/Pictures/577383.jpg)"'' http://localhost:8000/api/v1/users/register/ – Moreno Mar 10 '16 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.