![](/img/trans.png)
[英]how to get the image from the url without downloading it but store it in a variable in ruby
[英]Downloading image from url in Ruby and Rails
我正在嘗試從紅寶石和Rails的url下載圖像,到目前為止我所做的是
require 'base64'
parsedUri = URI.parse('http://somewebsite.com/path/to/image.jpeg')
http = Net::HTTP.new(parsedUri.host, parsedUri.port)
if params[:src].include? "https"
http.use_ssl = true
end
request = Net::HTTP::Get.new(parsedUri.request_uri, {'User-Agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0'})
response = http.request(request)
image = Base64.encode64(response.body)
File.open('some.jpeg', "w+") do |f|
f.write(image)
end
,現在這段代碼確實在我的根目錄中創建了一個文件,但是當我打開它時,它給了我一個錯誤“解釋JPEG圖像文件時出錯(不是JPEG文件:以0x64 0x61開頭)”,具有諷刺意味的是,當我在gedit中打開該文件時並使用相同的base64編碼,以使用img標簽在瀏覽器中呈現圖像。 圖像被渲染。 我正在使用Ubuntu。 請幫助它使我發瘋
不需要Base64.encode64
部分。 我刪除了它,並對代碼進行了一些重組:
uri = URI.parse('http://somewebsite.com/path/to/image.jpeg')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = params[:src].include?('https')
response = http.request(
Net::HTTP::Get.new(uri.request_uri, {
'User-Agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0'
})
)
File.open('some.jpeg', 'wb') { |f| f.write(response.body) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.