2013-07-28 82 views
1

我想让用户导入一个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 

就像一个魅力!

回答

1

Javascript无法将上传的文件发布到服务器,因为它是一个限制(出于安全原因,我假设)。

在张贴有关通过JavaScript发布这个文件的其他问题请看: JavaScript: Upload file

答案上质疑说,你只能使用闪光灯它做的,但也有上传和后期的iframe的替代品。

看看这个问题,以及一个可选的解决方案: https://github.com/Widen/fine-uploader

0

你的Ajax请求是不发送,你面前有你的onload函数返回的事件。
您可以使用XHR2在最新的浏览器上通过ajax发送文件

reader.onload = (function(theFile) { 
    var data = new FormData(); 
    data.append('file',theFile); 
    $.ajax({ 
    type: 'POST', 
    processData: false, 
    contentType: false, 
    url: "/parse_opml", 
    data: data, 
    success: function(details, response) { 
     console.log('woo!'); 
    }, 
    error: function(data, response) { 
     console.log('boooo'); 
    } 
    }); 
    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); 
    }; 
})(f); 
相关问题