Question

i'm tring to upload file using jquery ajax function with ruby-sinatra function. here is my code.

<form id="ucform" method="post" action="#" enctype="multipart/form-data">
  <input type="file" id="cfile" name="cfile" onchange="prepareUpload(this.files)">
  <button type="submit">Update</button>
</form>\

javascript code

var ufiles;
function prepareUpload(files)
{
  ufiles = files
}
$(function(){
  $('#ucform').on('submit', uploadFiles);
});



function uploadFiles(event)
{
    event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening
    //alert(ufiles);

    // Create a formdata object and add the files
    var data = new FormData();
    $.each(ufiles, function(key, value)
    {
        data.append(key, value);
    });


    alert(data);

    $.ajax({
        url: '/upload_cfiles',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR)
        {
        alert(data);    
        }
    });
}

sinatra function

post '/upload_cfiles' do
begin
    File.open('applications/QOS/conf/' + params['cfile'][:filename], "w") do |f|
        f.write(params['cfile'][:tempfile].read)
    end
    return "The file was successfully uploaded!"

rescue Exception => e
    return e.message
end

end

above code return bellow error

ERRORS: parsererror
undefined method `[]' for nil:NilClass

please help me to solve this error

Was it helpful?

Solution

It's a safe bet that params['cfile'] is nil. Have you actually logged your request parameters to ensure you are posting what you think you're posting?

Furthermore, I believe that you're trying to upload these files using JSON - you will most likely need to base64 encode the body of the file to do this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top