就像在
this Tutorial中描述的那样,我将画布转换为DataUrl,将此DataUrl转换为Blob.然后我发出一个ajax post请求,并希望使用Carrierwave将图像保存在数据库中.
这是我的JS代码:
uploadButton.on('click',function(e) { var dataURL = mycanvas.toDataURL("image/png;base64;"); // Get our file var file= dataURLtoBlob(dataURL); // Create new form data var fd = new FormData(); // Append our Canvas image file to the form data fd.append("image",file); // And send it $.ajax({ url: "/steps",type: "POST",data: fd,processData: false,contentType: false,}); }); // Convert dataURL to Blob object function dataURLtoBlob(dataURL) { // Decode the dataURL var binary = atob(dataURL.split(',')[1]); // Create 8-bit unsigned array var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } // Return our Blob object return new Blob([new Uint8Array(array)],{type: 'image/png'}); }
当我将以下代码添加到我的控制器时,图像得到了保存,但当然不是通过carrierwave.
File.open("#{Rails.root}/public/uploads/somefilename.png",'wb') do |f| f.write(params[:image].read) end
更新信息:
这些是我的ajax帖子请求的参数:
Parameters: {"image"=>#<ActionDispatch::Http::UploadedFile:0x007feac3e9a8a8 @tempfile=#<Tempfile:/var/folders/0k/q3kc7bpx3_51kc_5d2r1gqcc0000gn/T/RackMultipart20140211-1346-gj7kb7>,@original_filename="blob",@content_type="image/png",@headers="Content-Disposition: form-data; name=\"image\"; filename=\"blob\"\r\nContent-Type: image/png\r\n">}
Parameters: {"utf8"=>"✓","image"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007feac20c2e20 @tempfile=#<Tempfile:/var/folders/0k/q3kc7bpx3_51kc_5d2r1gqcc0000gn/T/RackMultipart20140211-1346-1ui8wq1>,@original_filename="burger.jpg",@content_type="image/jpeg",@headers="Content-Disposition: form-data; name=\"image[image]\"; filename=\"xy.jpg\"\r\nContent-Type: image/jpeg\r\n">}}
如果我做Image.create(params [:image])我有事务回滚…
事务回滚错误:
Unprocessable Entity ActiveRecord::RecordInvalid (Validation Failed: image You are not allowed to upload "" files,allowed types: jpg,jpeg,gif,png)