【问题标题】:how to upload file using ajax request with sinatra?如何使用带有 sinatra 的 ajax 请求上传文件?
【发布时间】:2014-05-13 22:04:53
【问题描述】:

我正在尝试使用带有 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

请帮我解决这个错误

【问题讨论】:

  • 你有什么理由使用 javascript 吗?

标签: javascript jquery ruby ajax sinatra


【解决方案1】:

可以肯定params['cfile'] 为零。您是否实际记录了请求参数以确保发布您认为发布的内容?

此外,我相信您正在尝试使用 JSON 上传这些文件 - 您很可能需要对文件的主体进行 base64 编码才能执行此操作。

【讨论】:

  • 是的,我已经在 firebug 请求正文中检查了一些编码字符串,包括文件名 n 等,我如何以 base64 格式编码正文??
猜你喜欢
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 2013-10-25
  • 2012-03-12
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 2018-08-28
相关资源
最近更新 更多