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
File.open(‘uploads/’ + params[‘myfile’][:filename], “w”) do |f|
f.write(params[‘myfile’][:tempfile].read)
end
end

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() {
$.post(’/run’);
});

I describe a route:
post ‘/run’ do
begin
filePath = ‘uploads/’ + params[:fileload][:filename]
File.open(filePath, “w+”) do |f|
f.write(params[‘fileload’][:tempfile].read)
end

settings.backend_process.async.run
rescue Exception => Err
Err.message
end
end

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) {
ev.preventDefault();

});

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