Reputation: 7068
I'm trying to figure out how to properly setup Carrierwave to be able to handle a file being sent via File Uploader.
I've attached fileuploader.js
and fileuploader.css
to my asset pipeline (rails 3.2.0) and have the following html:
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
</div>
And javascript:
$(document).ready(function(){
var uploader = new qq.FileUploader({
// pass the dom node (ex. $(selector)[0] for jQuery users)
element: $('#file-uploader')[0],
// path to server-side upload script
action: '/photos',
debug: true,
params: {
authenticity_token: "<%= form_authenticity_token.to_s %>"
},
onComplete: function(id, fileName, responseJSON){
alert(responseJSON.toString());
}
});
});
When I select a file it kicks off the script and my application gets called. That is what I don't know how to handle.
I have a Photo
model which has mount_uploader :image, ImageUploader
. Therefore in PhotoController
I have:
def create
io = AppSpecificStringIO.new(request.raw_post,params[:qqfile])
@photo = Photo.new(:image => io)
if @photo.save
respond_to do |format|
format.js { render :josn => @photo.to_json(:methods => :success, :only => [:id, :image]) }
end
else
respond_to do |format|
format.js { render :josn => {:success=>false} }
end
end
end
The param only has qqfile
which is the file name. I found out that request.raw_post
has the data for the image. But I don't know what format it is (is it 64Bit or not). I've been trying to find any resource I could on the subject and trying out anything. One source on Carrierwave's wiki suggested to use a AppSpecificStringIO class.
class AppSpecificStringIO < StringIO
attr_accessor :filepath
def initialize(*args)
super(*args[1..-1])
@filepath = args[0]
end
def original_filename
File.basename(filepath)
end
end
On File Uploader's wiki there is a suggestion for CarrierWave, but I can't figure anything out there either. CarrierwaveStringIO
doesn't exist as far as I can see.
I just want to get an ajax solution to uploading images to Carrierwave. Thank you to anyone who can help me.
Upvotes: 5
Views: 3082
Reputation: 4381
I am using the rack-raw-upload gem
and then in my controller i am doing the following:
def create
if params[:qqfile]
## IE acts differently
file = params[:qqfile].is_a?(ActionDispatch::Http::UploadedFile) ? params[:qqfile] : params[:file]
@attachment.asset = file
xhr_create
else
super
end
end
def xhr_create
if @attachment.save
render :json => { success: true }
else
render :json => @attachment.errors.to_json
end
end
and in application.rb
config.middleware.use 'Rack::RawUpload', :paths => ['/attachments']
Upvotes: 3