diff --git a/spec/helpers_spec.cr b/spec/helpers_spec.cr index 1f797ea..df24ec3 100644 --- a/spec/helpers_spec.cr +++ b/spec/helpers_spec.cr @@ -84,4 +84,30 @@ describe "Macros" do response.headers["Content-Type"].should eq("text/plain") end end + + describe "#send_file" do + it "sends file with given path and default mime-type" do + get "/" do |env| + send_file env, "./spec/asset/hello.ecr" + end + + request = HTTP::Request.new("GET", "/") + response = call_request_on_app(request) + response.status_code.should eq(200) + response.headers["Content-Type"].should eq("application/octet-stream") + response.headers["Content-Length"].should eq("20") + end + + it "sends file with given path and given mime-type" do + get "/" do |env| + send_file env, "./spec/asset/hello.ecr", "image/jpeg" + end + + request = HTTP::Request.new("GET", "/") + response = call_request_on_app(request) + response.status_code.should eq(200) + response.headers["Content-Type"].should eq("image/jpeg") + response.headers["Content-Length"].should eq("20") + end + end end diff --git a/src/kemal/helpers/helpers.cr b/src/kemal/helpers/helpers.cr index 1300313..e4943f0 100644 --- a/src/kemal/helpers/helpers.cr +++ b/src/kemal/helpers/helpers.cr @@ -40,3 +40,20 @@ end def headers(env, additional_headers) env.response.headers.merge!(additional_headers) end + +# Send a file with given path and default `application/octet-stream` mime_type. +# +# send_file env, "./path/to/file" +# +# Optionally you can override the mime_type +# +# send_file env, "./path/to/file", "image/jpeg" +def send_file(env, path : String, mime_type : String? = nil) + file_path = File.expand_path(path, Dir.current) + mime_type = "application/octet-stream" unless mime_type + env.response.headers.add "Content-Type", mime_type + env.response.content_length = File.size(file_path) + File.open(file_path) do |file| + IO.copy(file, env.response) + end +end