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?
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.
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 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
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 %>"