Rails'link_to'立即下载图像,而不是在浏览器中打开它 [英] Rails 'link_to' to Download An Image Immediately Instead of Opening it in the Browser

查看:119
本文介绍了Rails'link_to'立即下载图像,而不是在浏览器中打开它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个link_to Rails帮助器,当点击时下载壁纸。但图像正在浏览器中加载,而不是立即下载。

I have a link_to Rails helper that downloads a wallpaper when clicked. But the image is loading in the browser instead of being downloaded immediately.

<%= link_to "1920x1080", @download.wallpapers[1].wallpaper.url %>

但是同时我有一个link_to Rails帮助器下载.exe格式的屏幕保护程序,但在这里它的工作原理是:文件正在下载。

But at the same time I have a link_to Rails helper that downloads a screensaver of .exe format but here it works as inteded: file being downloaded immediately.

<%= link_to "720p", @download.screensavers.first.screensaver.url %>

我应该添加或执行这些操作,以使图像不会在浏览器中打开,而是下载立即?

What should I add or do so that the images will not be opened in the browser but instead be downloaded immediately?

谢谢!

推荐答案

一般来说,这样做是在发送图像时设置相应的标题:

Generally, the cleanest way to do this is to set the appropriate header when sending the image:

Content-Disposition: attachment; filename=&lt;file name.ext&gt;

如果从文件系统提供文件,send_file方法将允许您适当地设置此标题:

The send_file method will allow you to set this header appropriately if you're serving the file from the filesystem:

http://api.rubyonrails.org/classes/ActionController/Streaming.html#method-i-send_file

如果文件存储在您的数据库,可以使用send_data:

If the file is stored in your database, you can use send_data instead:

http://api.rubyonrails.org/classes/ActionController/Streaming.html#method-i-send_data

这篇关于Rails'link_to'立即下载图像,而不是在浏览器中打开它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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