File Upload
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
1
class SomeController < ApplicationController
2
def file_upload
3
image = params.files["image1"]
4
filename = image.filename
5
# Be sure to check if image.filename is not empty
6
# otherwise it'll raise a compile time error
7
if !filename.is_a?(String)
8
"No filename included in upload"
9
else
10
File.rename(image.file.path, "some/static/resources/#{filename}")
11
"Upload ok"
12
end
13
end
14
end
Copied!
Then in your routes file:
config/routes.cr
1
Amber::Server.configure do |app|
2
pipeline :web do
3
# pipelines...
4
end
5
6
routes :web do
7
# other routes,,,
8
post "/file_upload", SomeController, :file_upload
9
end
10
end
Copied!
You still require a form to upload your file, see views. Also see request and response.
Example slang file:
src/controllers/some_controller.cr
1
form action="/some/file_upload" method="post" enctype="multipart/form-data"
2
== csrf_tag
3
input type="file" name="file"
4
button type="Submit" Save
Copied!
Special thanks to Kemal Cookbook and Nocturne Project.
Last modified 2yr ago
Copy link