问题描述
我试图使用 SEND_DATA
返回一个PNG图像作为一个AJAX POST请求的响应。我如何让浏览器触发的成功回调下载?
详细信息
我生成使用 canvas.toDataURL()一个大的base64图片
,然后将其发布到滑轨(v3.2.6)。 Rails的德codeS到一个二进制PNG,并将图像返回给客户端。
我也试过由send_file
,但它有同样的问题。
其他选项
-
下载图像客户端::我们不能做到这一点,因为(1)的,和(2) Safari浏览器还不支持锚标记的下载属性我需要指定下载的图像文件名。
-
使用
$获得
而不是$交
:我们不能做到这一点,因为我们需要把我们的canvas.toDataURL()
的请求到服务器。GET
请求的URI有大小限制。
在控制器上创建功能
高清ajax_download
由send_file文件路径/+参数[:文件]
结束
,然后在控制器动作
的respond_to办|格式|
@java_url =/家/ ajax_download?文件=#{FILE_NAME}
format.js {渲染:部分=> 下载文件}
结束
,并在视图文件夹名称的部分与_downloadFile.js.erb写这行
window.location.href =<%= @ java_url%>中
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?
Details
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.
I've also tried send_file
but it has the same issue.
Other options
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.
Use a
$.get
instead of$.post
: We can't do this because we need to send ourcanvas.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
and then in controller action
respond_to do |format|
@java_url = "/home/ajax_download?file=#{file_name}"
format.js {render :partial => "downloadFile"}
end
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!