使用开放 URI 和大小小于 10kb 的回形针存储图像
我想从我的旧网站导入一些图标。这些图标的大小小于 10kb。因此,当我尝试导入图标时,它会返回 stringio.txt 文件。
require "open-uri"
class Category < ActiveRecord::Base
has_attached_file :icon, :path => ":rails_root/public/:attachment/:id/:style/:basename.:extension"
def icon_from_url(url)
self.icon = open(url)
end
end
在耙子任务中。
category = Category.new
category.icon_from_url "https://xyz.com/images/dog.png"
category.save
I want to import some icons from my old site. The size of those icons is less than 10kb. So when I am trying to import the icons its returning stringio.txt file.
require "open-uri"
class Category < ActiveRecord::Base
has_attached_file :icon, :path => ":rails_root/public/:attachment/:id/:style/:basename.:extension"
def icon_from_url(url)
self.icon = open(url)
end
end
In rake task.
category = Category.new
category.icon_from_url "https://xyz.com/images/dog.png"
category.save
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试:
Try:
要覆盖 Paperclip 中“假文件上传”的默认文件名(小文件上的
stringio.txt
或大文件上几乎随机的临时名称),您有两种主要可能性:定义一个
original_filename IO 上的
:您还可以从 URI 获取文件名:
或者替换
:path
中的:basename
:请记住始终更改
:网址
时您更改:path
,否则icon.url
方法将是错误的。您还可以定义自己的自定义插值(例如
:rails_root/公共/:无论如何
)。To override the default filename of a "fake file upload" in Paperclip (
stringio.txt
on small files or an almost random temporary name on larger files) you have 2 main possibilities:Define an
original_filename
on the IO:You can also get the filename from the URI:
Or replace
:basename
in your:path
:Remember to alway change the
:url
when you change the:path
, otherwise theicon.url
method will be wrong.You can also define you own custom interpolations (e.g.
:rails_root/public/:whatever
).我想你已经快到了,尝试打开解析的 uri,而不是字符串。
当然这不处理错误
You are almost there I think, try opening parsed uri, not the string.
Of course this doesn't handle errors
您还可以禁用 OpenURI 创建 StringIO 对象,并强制它创建临时文件。请参阅这个答案:
为什么 Ruby open-uri 的 open 在我的单元测试中返回 StringIO,但在我的控制器中返回 FileIO?
You can also disable OpenURI from ever creating a StringIO object, and force it to create a temp file instead. See this SO answer:
Why does Ruby open-uri's open return a StringIO in my unit test, but a FileIO in my controller?
过去,我发现检索远程文件最可靠的方法是使用命令行工具“wget”。以下代码大部分是直接从现有的生产 (Rails 2.x) 应用程序复制而来,并进行了一些调整以适合您的代码示例:
rake 任务逻辑可能如下所示:
这使用 mime-types gem 进行内容类型发现:
In the past, I found the most reliable way to retrieve remote files was by using the command line tool "wget". The following code is mostly copied straight from an existing production (Rails 2.x) app with a few tweaks to fit with your code examples:
The rake task logic might look like:
This uses the mime-types gem for content type discovery: