我試圖將html5 canvas的內容保存到我的Rails應用程序。我發現將html5 canvas輸出保存到我的rails應用程序
var url = canvas.toDataURL('image/png');
但我無法弄清楚如何進入我的文章/表單。
我使用carrierwave處理圖像,而不是上傳圖像我希望用戶在畫布上繪製一個圖像。
我在想的東西等形式的輸入文件設置此內容,但似乎並沒有爲它工作
的方式或者,也許我不應該使用的載波?
謝謝
我試圖將html5 canvas的內容保存到我的Rails應用程序。我發現將html5 canvas輸出保存到我的rails應用程序
var url = canvas.toDataURL('image/png');
但我無法弄清楚如何進入我的文章/表單。
我使用carrierwave處理圖像,而不是上傳圖像我希望用戶在畫布上繪製一個圖像。
我在想的東西等形式的輸入文件設置此內容,但似乎並沒有爲它工作
的方式或者,也許我不應該使用的載波?
謝謝
只需將url的內容放置在隱藏字段中。
<input type="hidden" name="canvascontent" id="canvascontent" />
在JavaScript(使用jQuery):
var url = canvas.toDataURL('image/png');
$("#canvascontent").val(url);
接受的答案沒有涵蓋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
然後在我的「創建」動作中,我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/
它確實讓我字節右場,但Carrierwave不似乎把它撿起來,並沒有被保存到數據庫。 – Jepzen 2012-02-02 22:34:26