簡體   English   中英

如何使用帶有sinatra的ajax請求上傳文件?

[英]how to upload file using ajax request with sinatra?

我正在嘗試使用帶有ruby-sinatra函數的jquery ajax函數上傳文件。 這是我的代碼。

<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代碼

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函數

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

結束

上面的代碼返回以下錯誤

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

請幫我解決這個錯誤

可以肯定的是, params['cfile']為零。 您是否實際記錄了請求參數以確保發布了您認為要發布的內容?

此外,我相信您正在嘗試使用JSON上傳這些文件-您很可能需要對文件正文進行base64編碼才能執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM