如何使用来自 AJAX 帖子的 Rails send_data 触发下载 [英] How to trigger download with Rails send_data from AJAX post

查看:26
本文介绍了如何使用来自 AJAX 帖子的 Rails send_data 触发下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 send_data 返回一个 PNG 图像作为对 ajax 发布请求的响应.如何让浏览器在成功回调时触发下载?

I'm trying to use send_data to return a PNG image as the response for a ajax post request. How do I get the browser to trigger a download on the success callback?

我正在使用 canvas.toDataURL() 生成一个大型 base64 图像,然后将其发布到 Rails (v3.2.6).Rails 将其解码为二进制 PNG,并将图像发送回客户端.

I'm generating a large base64 image using canvas.toDataURL(), and then posting it to Rails (v3.2.6). Rails decodes it to a binary PNG, and sends the image back to the client.

我也试过 send_file 但它有同样的问题.

I've also tried send_file but it has the same issue.

  1. 下载图片客户端:我们不能这样做,因为 (1) Safari 在大型 base64 URL 上崩溃,并且 (2) Safari 还没有支持锚标签上的下载属性,我需要指定下载的图像文件名.

  1. Download image client side: We can't do this because (1) Safari crashes on large base64 URLs, and (2) Safari does not yet support the download attribute on anchor tags which I would need to specify the downloaded image filename.

使用 $.get 而不是 $.post: 我们不能这样做,因为我们需要发送我们的canvas.toDataURL() 带有对服务器的请求.GET 请求 URI 有大小限制.

Use a $.get instead of $.post: We can't do this because we need to send our canvas.toDataURL() with the request to the server. GET requests URIs have size limitations.

推荐答案

在控制器中创建一个函数

create a function in controller

def ajax_download
  send_file "path_to_file/" + params[:file]
end

然后在控制器动作中

respond_to do |format|
  @java_url = "/home/ajax_download?file=#{file_name}"
  format.js {render :partial => "downloadFile"}
end

并使用_downloadFile.js.erb 制作部分视图文件夹名称并写下这一行

and make a partial in view folder name with _downloadFile.js.erb and write this line

window.location.href = "<%=@java_url %>"

这篇关于如何使用来自 AJAX 帖子的 Rails send_data 触发下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆