Sinatra & JQuery: file upload

Hello everybody!

I’m working on a small application. One of subtasks is file uploading.
There are many recipes - all of them suggest using the form, e.g.:

post “/upload” do‘uploads/’ + params[‘myfile’][:filename], “w”) do |f|

This actually works when the form with submit button is used, if I
initiate POST request with JQuery - it doesn’t. What do I actually do.

I declare a scriptblock in the body’s container in my view:
$(‘body’).on(‘click’, ‘#btn_run’, function() {

I describe a route:
post ‘/run’ do
filePath = ‘uploads/’ + params[:fileload][:filename], “w+”) do |f|
rescue Exception => Err

And, of course, there is an input HTML element with name=“fileload”.

As I can see in my console POST /run is sent successfully, the server
initiates backend process, but file uploading is not performed. Params
hash is empty.

I can’t use the form, because it breaks my event subscription while it
performs POST request. When I try to use JQuery’s preventDefault:

$(“form#upload_form”).submit(function(ev) {


It causes undefined method `[]’ for nil:NilClass
And, again, last stands for the string with params hash.

I don’t understand why does JQuery breaks Sinatra’s params hash. How do
I upload a file in such a situation?

I would appreciate any help, thanks in advance.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs