2014-12-01 46 views
4

我已經在互聯網上嘗試了一百萬個不同的教程,以瞭解如何從我的iOS應用程序上傳Base64圖像到我的Rails應用程序。似乎無論我如何格式化請求,它都不會被接受。如何將Base 64圖像上傳到Rails回形針

有誰知道如何將Base64圖像上傳到回形針嗎?

我試圖發送PARAM作爲JSON

{ "thumbnail_image": "base64_data..." } 

我還試圖把數據附加URL

{ "thumbnail_image": "data:image/jpeg;base64,alkwdjlaks..." } 

我試圖發送JSON對象使用和不使用數據鏈接

{ "thumbnail_image": { "filename": "thumbnail.jpg", "file_data": "base64_data...", "content_type": "image/jpeg" } } 

我始終得到這些Paperclip::NoHandlerError s,然後它將一大堆數據轉移到我的lo G。

回答

1

這是我如何在過去做到了,它基本上是一個強力的辦法,不知道是否紙夾在最近版本中添加了更好的支持,但這應該工作

class FooBar < ActiveRecord::Base 
    has_attached_file :thumbnail_image 
    validates_attachment_content_type :thumbnail_image, 
            content_type: %w(image/jpeg image/jpg image/png image/gif), 
            message: "is not gif, png, jpg, or jpeg." 

    attr_accessor :base64_thumbnail_image 

    # call this explicitly from the controller or in an after_save callback 
    # after setting the base64_thumbnail_image attribute 
    def save_base64_thumbnail_image 
    if base64_thumbnail_image.present? 
     file_path = "tmp/foo_bar_thumbnail_image_#{self.id}.png" 
     File.open(file_path, 'wb') { |f| f.write(Base64.decode64(base64_thumbnail_image)) } 
     # set the paperclip attribute and let it do its thing 
     self.thumbnail_image = File.new(file_path, 'r') 
    end 
    end 
end 

# params should be base64_thumbnail_image, not thumbnail_image in this case 
+0

這看起來很有希望。它吸吮回形針基本上忽略了什麼已成爲最常見的圖像提交格式之一:( – OneChillDude 2014-12-01 18:16:34

+0

不幸的是我得到了這個錯誤。它實際上並沒有引發異常,但沒有保存圖像'內容類型欺騙:文件名thumbnail18。 png([「image/png」]),從文件command:text/plain中發現的內容類型。請參閱文檔以允許此組合。' – OneChillDude 2014-12-01 18:24:00

+0

@BrianWheeler - 這是一個單獨的問題 - 您需要在模型上添加'validates_attachment_content_type'對於你允許的任何圖像類型 - 我將添加到代碼示例上面 – house9 2014-12-01 19:13:31

8

你的Base64編碼字符串似乎沒問題。你總是可以檢查,here

所以這個問題可能是在Rails方面。檢查您收到的字符串是否與發送的字符串完全相同。

用回形針4.2.1我設法挽救Base64的GIF文件的方式:

有:

class Thing 
    has_attached_file :image 

和POST屬性:

{ 
    "thumbnail_data:" "data:image/gif;base64,iVBORw0KGgo..." 
} 

所有你需要做的是找到適當的適配器並指定original_filename。所以對於控制器來說,這將是:

def create 
    image = Paperclip.io_adapters.for(params[:thumbnail_data]) 
    image.original_filename = "something.gif" 
    Thing.create!(image: image) 
    ... 
end 

AFAIK回形針使得從版本3.5.0更容易保存base64。

希望有幫助!

+0

正則表達式。事實上,至少在Paperclip 3.5.4中起作用。不過,它在第3.4.2節中不起作用。 – JellicleCat 2015-06-24 16:03:36

相關問題