Uploading a local image using the API

Hi Tony,

I agree uploading local files can be a bit tricky to figure out using the API. This should do the trick:

# upload_image.rb
require 'discourse_api'
require 'fileutils'

client = DiscourseApi::Client.new("Discourse Site URL")
client.api_key = "Your api key"
client.api_username = "Username"

filename = ARGV[1] #full path to file /home/tony/mypic.png

args = {
  :file => Faraday::UploadIO.new(filename, 'image/png')
}

resp = client.upload_file(args)

url = resp['url']
width = resp['width']
height = resp['height']



# topic_id is the the id for the topic you want to upload the image to.
args = {
  :topic_id => ARGV[0],
  :raw => "<img src=\"#{url}\" width=\"#{width}\" height=\"#{height}\">"
}

# This will create a new post in the specified topic
resp = client.create_post(args)

This will use the Faraday gem to provide the correct file requirements for upload_file. Once the file is uploaded, it then needs to be assigned to a topic/post to show up or it will be auto deleted.

You can call this script with

ruby upload_image.rb <topic_id> <filename>
ruby upload_image.rb 128 /home/tony/mypic.png