1

我有一個Image模型,需要我設置一些數據才能保存圖像,因爲我決定將圖像上傳到哪裏以及如何命名取決於模型中的一些數據。現在我正在嘗試:CarrierWave添加ActionDispatch :: Http :: UploadedFile模型處理後

# ImagesController sets up data 
img = Image.new 
img.imageable = user 
phashion_img = Phashion::Image.new(file.path) 
img.image_hash = phashion_img.fingerprint.to_s 
img.batch = img.latest_batch + 1 
img.extension = 'jpg' 
img.height = 640 
img.width = 640 

# ImageUploader uses it 
version :original do 
    def full_filename 
    "#{model.image_hash}/orig/#{alnum_encode(model.imageable.id)}.#{model.extension}" 
    end 
end 

我遇到了一個問題,試圖將上傳的圖像傳遞到上傳器。

img.uploader.store! file給我的錯誤wrong number of arguments (1 for 0) img.uploader.store! file.tempfile給我You are not allowed to upload "" files, allowed types: jpg, jpeg, gif, png

僅供參考,file是:

#<ActionDispatch::Http::UploadedFile:0x00000109ccdb70 @tempfile=#<Tempfile:/var/folders/lx/xk8vzr4s0fdd_m5w0syftfl80000gn/T/RackMultipart20140723-28731-1b5weu8>, @original_filename="20140522_164844.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"user[images_attributes][0][uploader]\"; filename=\"20140522_164844.jpg\"\r\nContent-Type: image/jpeg\r\n"> 

這將使file.tempfile:

#<Tempfile:/var/folders/lx/xk8vzr4s0fdd_m5w0syftfl80000gn/T/RackMultipart20140723-28731-1b5weu8> 

有什麼辦法我可以通過這些對象之一,ActionDispatch::Http::UploadedFileTempfile,轉發給Carrierwave上傳器?我可以對他們做一些轉變,以便上傳者可以接受他們中的一個?

回答

0

由於我的使用案例與CarrierWave或其他任何圖片上傳工具的用途相差甚遠,因此我最終使用AWS-SDK gem將自己的解決方案上傳到S3。這是非常具體的,但我把它的主旨發佈在它幫助別人的機會上。

# Image processing 
magick = Magick::Image.from_blob(file.read)[0] 

if !["JPG", "JPEG", "GIF", "PNG"].include? magick.format 
    # Invalid format specified 
end 

orig = Image.new 
orig.imageable = user 
phashion_img = Phashion::Image.new(file.path) 
orig.image_hash = phashion_img.fingerprint.to_s 
orig.batch = orig.latest_batch + 1 
orig.extension = magick.format.downcase 
filename = "#{orig.image_hash}/orig/#{Alnum.encode(orig.imageable_id)}.#{orig.extension}" 
orig.height = magick.rows 
orig.width = magick.columns 
orig.size = 'orig' 

# Upload to S3 
s3 = AWS::S3.new 
uploaded_name = Rails.root.to_s+filename.gsub('/', '_') 
magick.write(uploaded_name) # Save file to filesystem so I can upload to S3 
s3.buckets[bucket_name].objects[filename].write(open(uploaded_name), :acl => :public_read) 
FileUtils.rm uploaded_name # Remove so it's not taking up space 

# Crop 
cropped = magick.crop(x.to_i, y.to_i, w.to_i, h.to_i, true) # Discard offset data to avoid borders 

# Create Profile 
# Resize_from is my own custom function to copy everything 
# but the size into another object and resize the image 
resize_from(s3, orig, cropped, 640, 640) 

# Create Grid 
resize_from(s3, orig, cropped, 220, 220) 

# Create Thumbnail 
resize_from(s3, orig, cropped, 72, 72) 
相關問題