开发者

Paperclip: Assign an image programmatically and set its name

Using Paperclip, I want to grab an image from a URL like this:

require 'open-uri'

user.photo = open(url)

The problem is that I then wind up with a filename like 'open-uri20110915-4852-1o7k5uw'. 开发者_运维百科Is there any way I can change the filename on user.photo?

As an added twist, Paperclip is storing my files on S3, so it'd be even better if I could set the filename I want in the initial assignment, so images get uploaded to the right S3 key. Something like this:

user.photo = open(url), :filename => URI.parse(url).path


You can write the filename back to your instance via:

 photo.instance_write(:file_name, new_file_name)

So if your source URL is like:

 http://example.com/foo.jpg

You can first parse the name from the URL (to get foo.jpg) and then write it back to the instance using the above instance_write method.


io = open(url)
def io.original_filename; base_uri.path.split('/').last; end

This will set the filename to the filename in the url.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜