本文介绍了水晶郎如何从HTTP获取二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中:

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

如何在Crystal中做同样的事情?

How to do the same in Crystal?

推荐答案

我们可以执行以下操作:

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

这仅将响应写入而没有任何HTTP标头到文件中. File.write也很聪明,不必首先将整个文件下载到内存中,而是在从给定的IO中读取块时写入文件.

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.

这篇关于水晶郎如何从HTTP获取二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 09:11