Uploading a remote file url from Rails Console with Carrierwave

江枫思渺然 提交于 2019-11-30 03:14:15

Take a look at the 'Uploading files from a remote location' section on this page https://github.com/carrierwaveuploader/carrierwave

CarrierWave should throw an error if the url of the location is invalid

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

Or if it's an unknown host:

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

Please also note that if you want to download remote images you should prefix the attribute with remote_ and suffix it with _url, as shown in the example

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

FILE_LOCATION can be

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

if file is found in a folder 'files' in rails project

I was facing the same problem. and the issue might be http is redirecting to https. So I replaced them using gsub as follows:

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

this should most probably solve the problem.

I have had problems with remote_avatar_url not uploading the image or throwing any errors. For me, as far as I can tell, it was because I set the following in my model.

attr_accessor :remote_avatar_url

Carrierwave covers this for you, and although I don't understand why, setting it yourself buggers things up.

Is work as:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!