File Upload

Last updated 6 months ago

This recipe will help you to setup a basic file upload action in your application.

First you need an amber project generated with Amber CLI or from scratch.

src/controllers/some_controller.cr
class SomeController < ApplicationController
def file_upload
image = env.params.files["image1"]
filename = image.filename
# Be sure to check if image.filename is not empty
# otherwise it'll raise a compile time error
if !filename.is_a?(String)
"No filename included in upload"
else
File.rename(image.file.path, "some/static/resources/#{filename}")
"Upload ok"
end
end
end

Then in your routes file:

config/routes.cr
Amber::Server.configure do |app|
pipeline :web do
# pipelines...
end
‚Äč
routes :web do
# other routes,,,
post "/file_upload", SomeController, :file_upload
end
end

You still require a form to upload your file, see views. Also see request and response.

Special thanks to Kemal Cookbook and Nocturne Project.