rails download files by post request

刚做了一个下载文件,用的是get请求

1.先说用get请求:

window.location.href = "<%=ajax_batch_tracking_code_campaigns_url %>"
def ajax_batch_tracking_code
    file_path = Campaign.generate_tarcking_code_excel(params[:ids],client)
    send_file(file_path)
  end

 get请求会把参数带到url上,因为get请求的url长度有限制,所以当参数过长时get请求并不适用,所以研究了下怎么用post请求下载文件。

2.模拟一个form表单提交,这样是同步的:

var config = {method: 'post', url: '<%= ajax_batch_tracking_code_pretargetings_url()%>', data: {ids: BatchProcess.selected_ids().join(',')}};
var $form = $('<form method="' + config.method + '" />');
$form.attr('action', config.url);
for (var key in config.data) {
    $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
}
$(document.body).append($form);
$form[0].submit();
$form.remove();

  

 def ajax_batch_tracking_code
    file_path = Campaign.generate_tarcking_code_excel(params[:ids],client)
    send_file(file_path)
  end

 这样就可以通过post请求来达到下载文件的目的了。这时候需求又来了,点击下载按钮时,需要给页面上一个loading,当文件下载成功后loading消失,因为这种通过post请求的方式是同步的,没办法让loading消失(捕捉不到下载成功的事件),为了达到这个目的,可以用第三种方式:

3.通过ajax发送异步请求:

$.ajax({
              url : "<%= ajax_batch_tracking_code_pretargetings_url %>",
              type : "POST",
              data : {ids: BatchProcess.selected_ids().join(','), client_id: <%= @client.id%>},
              success : function(data) {
                  $("#ajax-loading_icon").hide();
              },
              error : function(data) {
                  console.log(data)
              }
          });

 controller#action代码如下

def ajax_batch_tracking_code
    file_name = Campaign.generate_tarcking_code_excel(params[:ids],client)
    respond_to do |format|
      @file_url = request.url.split(/zh-cn|en/)[0] + 'tracking_code/otv/' + file_name
      format.js {render :partial => "downloadFile"}
    end
  end

 另外需要建一个名为_downloadFile.js.erb的文件,文件内容如下:

 window.location.href = "<%=@file_url %>";

猜你喜欢

转载自wangsuting.iteye.com/blog/2308892