使用Ruby将png图像发布到pngcrush

时间:2015-06-13 16:17:22

标签: ruby http post png

在ruby中,我希望获得与下面的代码相同的结果,但不使用curl:

curl_output = `curl -X POST -s --form "input=@#{png_image_file};type=image/png" http://pngcrush.com/crush >  #{compressed_png_file}`

我试过了:

#!/usr/bin/env ruby
require "net/http"
require "uri"

# Image to crush
png_image_path = "./media/images/foo.png"

# Crush with http://pngcrush.com/
png_compress_uri = URI.parse("http://pngcrush.com/crush")
png_image_data = File.read(png_image_path)
req = Net::HTTP.new(png_compress_uri.host, png_compress_uri.port)
headers = {"Content-Type" => "image/png" }
response = req.post(png_compress_uri.path, png_image_data, headers)

p response.body
# => "Input is empty, provide a PNG image."

1 个答案:

答案 0 :(得分:1)

您的代码存在的问题是您没有向服务器发送必需的参数(http://pngcrush.com/crush的“输入”)。这对我有用:

require 'net/http'
require 'uri'

uri = URI.parse('http://pngcrush.com/crush')

form_data = [
  ['input', File.open('filename.png')]
]

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new uri

# prepare request parameters
request.set_form(form_data, 'multipart/form-data')
response = http.request(request)

# save crushed image
open('crushed.png', 'wb') do |file|
  file.write(response.body)
end

但我建议您使用RestClient。它将ne​​t / http封装在很酷的功能中,比如多部分表单数据,只需要几行代码就可以完成这项工作

require 'rest_client'

resp = RestClient.post('http://pngcrush.com/crush',
  :input => File.new('filename.png'))

# save crushed image
open('crushed.png', 'wb') do |file|
  file.write(resp)
end

使用gem install rest-client

进行安装