title: How to send image as base64 string in JSON using HTTP POST?
body: <p>I'm trying to upload an image from user's computer. First I read the image as a binary string, then encode it in base64 and then POST it as part of a JSON object. However, I get a HTTP 500 error and I have no idea why. I have tried replacing reader.result with a hardcoded short string and it worked (I got a HTTP 200). So I'm not sure if the string length (which is very long for an image binary string) is the major factor here. The domain from which the POST is being sent and received are different if that matters. What could be wrong here? Thanks in advance.</p>
  
  <p>Error message:</p>
  
  <blockquote>
    <p>[2014-01-11 14:23:58] INFO  WEBrick::HTTPServer#start: pid=77263
    port=9292
    127.0.0.1 - - [11/Jan/2014 14:24:37] "POST /pull_request HTTP/1.1" 500 185316 0.0413</p>
  </blockquote>
  
  <p>Client side code:</p>
  
  <pre><code>if(image &amp;&amp; image.type.match(imageType)) {
      var fileName = timestamp+'-'+image.name;
      var reader = new FileReader();
      reader.onload = function(e) {
          write('images/'+fileName, Base64.encode(reader.result), 'base64');
      };
      reader.readAsBinaryString(image);
  }
  
  function write(path, content, encoding){
      var request = {"request":{"path": path, "content": content, "encoding": encoding}};
      $.ajax({
          type: "POST",
          url: "http://localhost:9292/upload",
          data: JSON.stringify(request)
      });
  
  }
  </code></pre>
  
  <p>Server side code. I removed the JSON parsing and upload stuff for simplicity because at the moment I just want to get a HTTP 200 whenever I receive a POST, regardless of data content:</p>
  
  <pre><code>require 'sinatra'
  require 'json/ext' # required for .to_json
  require 'github_api'
  
  configure do
      username = ENV['GITHUB_USER'] || 'username'
      password = ENV['GITHUB_PASSWORD'] || 'password'
      github_login = "%s:%s"  % [username, password]
      github = Github.new basic_auth: github_login
      set :github, github
      set :user_name, 'someusername'
      set :repo, 'somerepo'
  end
  
  post "/request" do
      status 200
  end
  </code></pre>