使用Carrierwave在Rails Console上传远程文件URL

40
我只是想知道如何在Rails控制台中使用Carrierwave上传远程文件URL。我尝试了以下方式,但都没有成功。我猜测它没有处理Uploader?
user = User.first
user.remote_avatar_url = "http://www.image.com/file.jpg"
user.save

非常感谢


1
这是正确的语法。你的development.log文件显示了什么? - Jesse Wolgamott
1
当然,这假定用户使用 mounts_uploader :avatar - Jesse Wolgamott
感谢您的回复,Jesse。我是用户mount_uploader:avatar,AvatarUploader。我的日志实际上没有显示任何内容。我一定是漏掉了什么。在浏览器中运行得很好。 - Wasabi Developer
好的,看起来现在它正在工作。我必须在我的 Vagrant VM 的 SSH 中运行它。 - Wasabi Developer
5个回答

27

请查看此页面上的“从远程位置上传文件”部分:https://github.com/carrierwaveuploader/carrierwave

如果位置的 URL 无效,CarrierWave 应该抛出一个错误。

2.1.3 :015 > image.remote_image_url = "http"
 => "http"
2.1.3 :016 > image.save!
   (0.2ms)  BEGIN
   (0.2ms)  ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Image trying to download a file which is not served over HTTP

或者如果它是一个未知的主机:

2.1.3 :017 > image.remote_image_url = "http://foobar"
=> "http://foobar"
2.1.3 :018 > image.save!
   (0.4ms)  BEGIN
   (0.4ms)  ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Image could not download file: getaddrinfo: nodename nor servname provided, or not known

请注意,如果您想要下载远程图片,则应该在属性前加上remote_前缀,并在末尾加上_url后缀,如示例所示。


我遇到了一个问题,当我创建新条目并使用image.remote_image_url =“somevalidurl”保存远程URL时,它可以正常工作,但是当我更新时,它不会更新新的图像。 - Manwal

7
user = User.first
user.remote_avatar = File.open(FILE_LOCATION)
user.save

FILE_LOCATION 可以是:

File.join(Rails.root, '/files/png-sample.png')

如果在Rails项目的文件夹“files”中找到文件。

问题是如何从远程位置(远程URL)上传文件。不是我系统上的文件。 - Jason FB
1
如果是这样的话,只需使用方法 user.remote_avatar_url = "www.example.com/image.jpg",Carrierwave 将简单地下载文件并重新上传到您的应用程序中。 - Oss

5

我曾经遇到相同的问题,可能是因为HTTP重定向到了HTTPS。所以我使用gsub进行了替换,如下:

image.remote_image_url = remote_image_url.gsub('http://','https://')
image.save!

这应该可以解决问题。

-1

工作如下:

url='http://host.domain/file.jpg'    
time=Time.now.to_i.to_s
myfile=IO.sysopen("tmp/"+time+"_img."+url.split(".").last,"wb+")
tmp_img=IO.new(myfile,"wb")
tmp_img.write open(URI.encode(url)).read

if File.exist?("tmp/"+time+"_img."+url.split(".").last)
  "tmp/"+time+"_img."+url.split(".").last
  image = ActionDispatch::Http::UploadedFile.new(:tempfile => tmp_img, :filename => File.basename(tmp_img))
else 
  image=nil
end
@your_model.image=image
@your_model.save

-1

我遇到了remote_avatar_url无法上传图片或抛出任何错误的问题。据我所知,这是因为我在我的模型中设置了以下内容。

attr_accessor :remote_avatar_url

Carrierwave 已经为您覆盖了这一点,虽然我不明白为什么,但自己设置会搞砸事情。


1
如果你这样做,实际上会覆盖carrierwave对remote_avatar_url的声明。 - counterbeing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接