This is my wisdom how to upload an image via API v3 with perl (this code is easy to translate to other languages). I struggled because I thought that I have to take multipart/form-data, answer was “Please select an image”, but image-upload can be made much simpler with a simple form upload.
#!/usr/bin/perl
use Mojo::UserAgent;
use feature 'say';
use strict;
use warnings;
my $ua = Mojo::UserAgent->new;
my $ghost_base_url = "https://ghost.dummy.com";
# User has to be at least "author" role
my $username = 'me@dummy.com';
my $password = 'mypassword';
my $url;
my $tx;
# Login
$url = $ghost_base_url . "/admin/session";
$tx = $ua->post($url
=> {
Referer => $url,
}
=> json => {
username => $username,
password => $password,
}
);
if ($tx->result->is_success) {
say 'logged in';
} else {
die "Could not log in";
# . $tx->result->body;
}
# Image Upload, do not do any fancy things!
# NO Multipart because multipart gives back: "Please select an image."
# The description of the api did not work for me with multipart
# https://ghost.org/docs/api/v3/admin/?_ga=2.216236182.1227731172.1588941555-1911532722.1586081388#images
my $image_fqn = "/tmp/flower.png";
my $wanted_image_name_on_serverside = "flower.png";
$url = $ghost_base_url . "/ghost/api/v3/admin/images/upload/";
$tx = $ua->post(
$url,
{
'Referer' => $url,
},
form => {
file => {
'name' => 'file',
'Content-Type' => 'image/png',
# wanted filename on the server:
'filename' => $wanted_image_name_on_serverside,
# local filename
'file' => $image_fqn,
},
}
);
my $image_on_serverside_url;
if ($tx->result->is_success) {
say "Upload of $image_fqn was successful";
# This is what comes back as answer:
# {"images":[{"url":"https://ghost.dummy.com/content/images/2020/05/flower.png","ref":null}]}
$image_on_serverside_url = $tx->result->json->{images}->[0]->{url};
say "URL is $image_on_serverside_url";
} else {
say "Upload of $image_fqn was NOT successful";
say $tx->result->body;
die;
}