簡體   English   中英

使用Carrierwave從Rails控制台上傳遠程文件URL

[英]Uploading a remote file url from Rails Console with Carrierwave

我只是想知道如何使用Rails控制台中的Carrierwave上傳遠程文件url。

我沒有運氣就嘗試了以下方法。 我認為它沒有處理上傳器?

user = User.first
user.remote_avatar_url = "http://www.image.com/file.jpg"
user.save

非常感謝

看一下此頁面上的“ 從遠程位置上傳文件 ”部分https://github.com/carrierwaveuploader/carrierwave

如果位置的網址無效,則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_加上remote_並在其后綴_url ,如示例所示

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

FILE_LOCATION可以是

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

如果在rails項目的文件夾“文件”中找到文件

我面臨着同樣的問題。 可能是http正在重定向到https。 因此,我使用gsub替換了它們,如下所示:

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

這最有可能解決問題。

我遇到remote_avatar_url無法上傳圖像或引發任何錯誤的問題。 據我所知,這是因為我在模型中設置了以下內容。

attr_accessor :remote_avatar_url

Carrierwave可以為您解決這個問題,盡管我不明白為什么,但是自行設置它會使事情煩惱。

是作為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM