2012-02-02 12 views
2

html5キャンバスのコンテンツをRailsアプリに保存しようとしています。私は見つけたhtml5 canvas出力を自分のレールアプリに保存する

var url = canvas.toDataURL('image/png'); 

しかし、私はどのように私のポスト/フォームにそれを得るかを把握できません。

私は画像を処理するためにcarrierwaveを使用していますが、画像をアップロードするのではなく、ユーザーがキャンバスに描画します。

私はこのコンテンツにフォームの入力ファイルを設定するようなものを考えていたが、それはそれは

動作する方法ではないようですそれとも私は、搬送波を使用してすべきではありませんか?

おかげ

答えて

5

は単に隠しフィールドにURLのコンテンツを配置します。 (jQueryを使って)JavaScriptで

<input type="hidden" name="canvascontent" id="canvascontent" /> 

var url = canvas.toDataURL('image/png'); 
$("#canvascontent").val(url); 
+1

それは右のフィールドに私のバイトを取得しているが、Carrierwaveはそれを拾うように見えるいけないと何も保存されていませんデータベースに転送します。 – Jepzen

1

私はそれが私のアプリで働いていて、それがあるので、ここでcarrierwave部分をカバーしていない受け入れ答え:で

私profile_images_contoller.rb私は、以下の機能を追加しました:

# Convert base64 to binary 
def split_base64(uri_str) 
    if uri_str.match(%r{^data:(.*?);(.*?),(.*)$}) 
    uri = Hash.new 
    uri[:type] = $1 # "image/gif" 
    uri[:encoder] = $2 # "base64" 
    uri[:data] = $3 # data string 
    uri[:extension] = $1.split('/')[1] # "gif" 
    return uri 
    else 
    return nil 
    end 
end 

# Convert data uri to uploaded file. Expects object hash, eg: params[:profile_image] 
def convert_data_uri_to_upload(obj_hash) 
    if obj_hash[:remote_image_url].try(:match, %r{^data:(.*?);(.*?),(.*)$}) 
    image_data = split_base64(obj_hash[:remote_image_url]) 
    image_data_string = image_data[:data] 
    image_data_binary = Base64.decode64(image_data_string) 

    temp_img_file = Tempfile.new("data_uri-upload") 
    temp_img_file.binmode 
    temp_img_file << image_data_binary 
    temp_img_file.rewind 

    img_params = {:filename => "data-uri-img.#{image_data[:extension]}", :type => image_data[:type], :tempfile => temp_img_file} 
    uploaded_file = ActionDispatch::Http::UploadedFile.new(img_params) 

    obj_hash[:image] = uploaded_file 
    obj_hash.delete(:remote_image_url) 
    end 

    return obj_hash  
end 

その後、私の "作成" アクションI PAにssed convert_data_uri_to_upload(のparams [:profile_image])ProfileImage.newに()

def create 
    @profile_image   = ProfileImage.new(convert_data_uri_to_upload(params[:profile_image])) 
    @profile_image.imageable = @imageable 

    respond_to do |format| 
    if @profile_image.save 
     format.html { redirect_to @entity_redirect_edit_path, notice: 'Profile image was successfully created.' } 
     format.json { render json: @profile_image, status: :created, location: @profile_image } 
    else 
     format.html { render action: "new" } 
     format.json { render json: @profile_image.errors, status: :unprocessable_entity } 
    end 
    end 
end 

が出典:http://www.davehulihan.com/uploading-data-uris-in-carrierwave/