# Uploading a local image using the API

**URL:** <https://meta.discourse.org/t/uploading-a-local-image-using-the-api/127071>\
**Category:** Development\
**Created:** [August 28, 2019, 10:37pm UTC](https://meta.discourse.org/t/uploading-a-local-image-using-the-api/127071 "2019-08-28T22:37:28Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![blake](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/blake/32/157322_2.png) [@blake](https://meta.discourse.org/u/blake)\
**Post date:** [August 29, 2019, 1:13pm UTC](https://meta.discourse.org/t/uploading-a-local-image-using-the-api/127071/3 "2019-08-29T13:13:09Z")

</div>

Hi Tony,

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

```ruby
# 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

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

```

---

_[View the full topic](https://meta.discourse.org/t/uploading-a-local-image-using-the-api/127071)._
