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 %>";

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值