2

I'm trying to upload an image to a WordPress.com blog via their REST API. According to their documentation, I should be able to use the new post endpoint to do so. I'm currently using Rails and rest-client to successfully create text posts using the following code (post_hash contains all the post information):

  url = "https://public-api.wordpress.com/rest/v1/sites/" + @blog.external_id + "/posts/new"
  params = {
      pretty = true,
      title: post_hash[:post_title],
      content: post_hash[:post_content],
      categories: post_hash[:terms_names][:category],
      tags: post_hash[:terms_names][:post_tag]
  }
  headers = { authorization: "Bearer " + @oauth_token, content_type: :json }
  RestClient.post(url, params, headers)

As I mentioned, this works perfectly. Now, I'd like to be able to upload a new image to the blog's Gallery by creating a new "post" with the image attached. I'm trying to use this code to do so (image is a CarrierWave file stored on Amazon S3):

  url = "https://public-api.wordpress.com/rest/v1/sites/" + @blog.external_id + "/posts/new"
  image_data = open(image.to_s, "rb").read
  params = {
      format: "image", 
      media: [image_data], 
      multipart: true
  }
  headers = { authorization: "Bearer " + @oauth_token, content_type: image.content_type }
  RestClient.post(url, params, headers)

This does not work and keeps giving me a 400 Bad Request error. If anyone has any suggestions as to what I'm doing wrong or advice on a better way of doing this, I'd greatly appreciate it. Thanks!

4

0 回答 0