我要使用带有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
请帮我解决这个错误
答案 0 :(得分:0)
可以肯定params['cfile']
是零。您是否实际记录了请求参数以确保发布您认为发布的内容?
此外,我相信您正在尝试使用JSON上传这些文件 - 您很可能需要对文件正文进行base64编码才能执行此操作。