【问题标题】:How to initiate a download on the client site with jquery and rails?如何使用 jquery 和 rails 在客户端网站上启动下载?
【发布时间】:2013-10-11 01:28:41
【问题描述】:

我的 rails4 应用程序的控制器中有以下代码:

# resolve the soft links and archive all photos for the current download
archived_photos = archive_current_download_photos(current_downloads_dir)

respond_to do |format|

  if !File.exists?(archived_photos)
    format.json { 
      render :nothing => true, :status => 500
    }
  else
    format.json {
      send_file(archived_photos, :disposition => "attachment", :filename => "photos.zip", :type => 'application/zip')
    }
  end

end

以及javascript中的处理:

   download photos request

   ajax_download = (valuesToSubmit, download_url, http_method) ->

   # AJAX
   $.ajax
    type: http_method
    url: download_url #sumbits it to the given url of the form
    data: valuesToSubmit # form
    dataType: "json"
    error: (error) ->
      console.log("DEBUG: error")
      return
    success: (data) ->

      console.log("DEBUG: success")
      return

   return false

调用此函数时,我没有下载,但我看到数据已下载。

如何强制 Chrome 开始下载(不使用 link_to,而是在响应后立即开始下载)?

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax download


    【解决方案1】:

    尝试将window.location 设置为您的rails 应用程序的强制下载url 路径。?

    我想这应该可以工作,因为不会加载新页面并且强制下载会弹出文件。

    【讨论】:

    • 您能否更详细地解释一下 window.location - 在 ajax 成功中做到这一点?怎么样?
    • 你的意思是:添加window.location.href = <url to the file sent back with ajax> ?
    • 在成功回调时,设置这个window.location = 'http://download_url。它会重定向用户,但不应该很明显。
    【解决方案2】:

    您不能通过 ajax 调用强制下载文件。我认为 Chrome 支持它,但你不会得到一个可靠的跨浏览器解决方案来运行 IMO。

    最好的办法是使用window.location 或以下链接将用户发送到另一个页面:

    <a href='download_url' target='_blank'>click</a>
    

    【讨论】:

      猜你喜欢
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多