我想让用户导入一个OPML文件,我解析服务器(rails应用程序)端。我有麻烦,因为看起来我的服务器没有收到信息(成功和错误功能都没有运行,即使我将其他数据硬编码到呼叫中,呼叫也不会改变)。如何将文件的内容发送到我的服务器?
这里是我已经嵌入到页面中:
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Print the contents of the file
var span = document.createElement('span');
span.innerHTML = ['<p>',e.target.result,'</p>'].join('');
document.getElementById('list').insertBefore(span, null);
};
$.ajax({
type: 'GET',
url: "/parse_opml",
data: {file: f},
success: function(details, response) {
console.log('woo!');
},
error: function(data, response) {
console.log('boooo');
}
});
})(f);
// Read in the file
reader.readAsText(f);
}
}
document.getElementById('the_o').addEventListener('change', handleFileSelect, false);
</script>
<input id="the_o" name="files[]" type="file">
看着Chrome的网络面板,我看到电话:Request URL:blob:http%3A//localhost%3A3000/14e2be6b-059f-47f5-ba37-97eda06242b4
其预览和响应是我的.txt文件的内容。但正如我所说,服务器从来没有得到这个文本,所以我感到困惑。
任何帮助非常感谢,谢谢!
ANSWER
最后我只是用这样的:JavaScript: Upload file
客户端代码:
%form{:enctype => 'multipart/form-data', :action => '/parse_opml', :method => 'post'}
%input{:type => 'file', :name => 'file', :id => 'the_o'}
%input{:type => 'submit', :value => 'go'}
Server代码:
f = File.open(params[:file].tempfile, 'r')
c = f.read
就像一个魅力!