Skip to content

Instantly share code, notes, and snippets.

@mixflame
Created May 17, 2021 01:20
Show Gist options
  • Save mixflame/8be6f6ae13d5a5da2d3b8c88eac00ec6 to your computer and use it in GitHub Desktop.
Save mixflame/8be6f6ae13d5a5da2d3b8c88eac00ec6 to your computer and use it in GitHub Desktop.
def upload_to_imgur
path = params.files["picture"].file.path
file = File.open(path)
# file = IO::Memory.new("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
redis = Redis.new
# upload image to imgur
url = URI.parse("https://api.imgur.com/3/image")
io = IO::Memory.new
builder = HTTP::FormData::Builder.new(io, "----WebKitFormBoundary7MA4YWxkTrZu0gW")
builder.file("image", file, HTTP::FormData::FileMetadata.new(filename: "upload.png"))
builder.field("title", "Gbaldraw.fun #{Time.utc} GBALDA")
builder.field("description", "A snapshot of the gbaldraw.fun canvas at #{Time.utc}")
builder.field("name", "gbaldraw-#{Time.utc.month}-#{Time.utc.day}-#{Time.utc.year}-#{Time.utc.hour}:#{Time.utc.minute}:#{Time.utc.second}.png")
builder.field("type", "png")
builder.finish
client = HTTP::Client.new(url)
req = HTTP::Request.new("POST", "/3/image")
req.body = io.to_s
req.content_length = io.size
req.headers = HTTP::Headers{
"Authorization" => "Client-ID 3e035ba859d6add",
"Host" => "#{url.host}",
"Content-Type" => builder.content_type
}
response = client.exec(req)
# id = JSON.parse(response.body.to_s)["data"]["id"].to_s
# redis.rpush("gallery", id)
puts "Response code #{response.status_code}"
puts "File path: #{response.body.to_s}"
# {data: {link: "https://google.com"}.to_h}.to_h.to_json
response.body.to_s.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment