我试图让用户导入我解析服务器(rails 应用程序)端的 OPML 文件。我遇到了麻烦,因为我的服务器似乎没有获取信息(成功和错误函数都没有运行,即使我将其他数据硬编码到调用中,调用也不会改变)。
这是我嵌入页面的内容:
<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 文件的内容。但就像我说的,服务器永远不会得到那个文本,所以我很困惑。
非常感谢任何帮助,谢谢!
回答
我最终只使用了这个:JavaScript:上传文件
客户端代码:
%form{:enctype => 'multipart/form-data', :action => '/parse_opml', :method => 'post'}
%input{:type => 'file', :name => 'file', :id => 'the_o'}
%input{:type => 'submit', :value => 'go'}
服务器代码:
f = File.open(params[:file].tempfile, 'r')
c = f.read
奇迹般有效!