SeventhSon
SeventhSon

Reputation: 71

Crystal lang how to get binary file from http

In Ruby:

require 'open-uri'
download = open('http://example.com/download.pdf')
IO.copy_stream(download, '~/my_file.pdf')

How to do the same in Crystal?

Upvotes: 4

Views: 1050

Answers (2)

SeventhSon
SeventhSon

Reputation: 71

I found something that works:

require "http/request"
require "file"
res = HTTP::Client.get "https://ya.ru"
fl=File.open("ya.html","wb")
res.to_io(fl)
fl.close

Upvotes: 1

Jonne Haß
Jonne Haß

Reputation: 4857

We can do the following:

require "http/client"

HTTP::Client.get("http://example.org") do |response|
  File.write("example.com.html", response.body_io)
end

This writes just the response without any HTTP headers to the file. File.write is also smart enough to not download the entire file into memory first, but to write to the file as it reads chunks from the given IO.

Upvotes: 10

Related Questions