In a rails 2.3.11 app I'm trying to register file downloads that are availabl开发者_运维知识库e only to logged on users. When they click on the link to download the file (that is a direct link to a file in the public directory) I want the rails app to call a method.
I guess I should use link_to_function, I'm ok with writing the javascript/method in rails to record the download.
I don't know how I have to let the file download continue after the method has been called. After the method call (that is in the background), the file download should start.
Any ideas?
You're probably over-thinking this, there's no need for Javascript. What you want is a link to a download action, which in turn registers the download and then streams the file back. This should work fine unless you have a really large file that you don't want Rails to have to process.
An example of sending a binary file back from the controller:
send_data(binary_data, :type => 'application/pdf', :filename => 'myfile.pdf', :disposition => 'inline' )
or even better:
render :content_type => 'application/octet-stream', :text => Proc.new { |response, output|
# do something that reads data and writes it to output
}
The answer from Abdullah Jibaly works perfect is has the advantage of not needing Javascript.
I ended up implementing a jQuery javascript solution that leaves the file download as before.
The link in my view, adding the download class is important for the js to work:
<%= link_to document.type.value, document.scan.url, :popup => true, :class => "download" %>
The added javascript, I add a property_id as data to post, because I need that value in my controller:
<script type="text/javascript">
$(document).ready(function() {
$(".download").click(function(event){
$.post("/ajax/property_interested_user", { property_id: $("#property_id").html() });
});
});
</script>
精彩评论