Uploading images from Flex to Rails using Paperclip
- by 23tux
Hi everyone,
I'm looking for a way to upload images that were created in my flex app to rails. I've tried to use paperclip, but it don't seem to work.
I've got this tutorial here: http://blog.alexonrails.net/?p=218
The problem is, that they are using a FileReference to browse for files on the clients computer. They call the .upload(...) function and send the data to the upload controller. But I'm using a URLLoader to upload a image, that is modified in my Flex-App. First, here is the code from the tutorial:
private function selectHandler(event:Event):void {
var vars:URLVariables = new URLVariables();
var request:URLRequest = new URLRequest(uri);
request.method = URLRequestMethod.POST;
vars.description = "My Description";
request.data = vars;
var uploadDataFieldName:String = 'filemanager[file]';
fileReference.upload(request, uploadDataFieldName);
}
I don't know how to set that
var uploadDataFieldName:String = 'filemanager[file]';
in a URLLoader. I've got the image data compressed as a JPEG in a ByteArray. It looks like this:
public function savePicture():void {
var filename:String = "blubblub.jpg";
var vars:URLVariables = new URLVariables();
vars.position = layoutView.currentPicPosition;
vars.url = filename;
vars.user_id = 1;
vars.comic_id = 1;
vars.file_content_type = "image/jpeg";
vars.file_file_name = filename;
var rawBytes:ByteArray = new JPGEncoder(75).encode(bitmapdata);
vars.picture = rawBytes;
var request:URLRequest = new URLRequest(Data.SERVER_ADDR + "pictures/upload");
request.method = URLRequestMethod.POST;
request.data = vars;
var loader:URLLoader = new URLLoader(request);
loader.addEventListener(Event.COMPLETE, savePictureHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandlerUpload);
loader.load(request);
}
If I set the var.picture URLVariable to the bytearray, then I get the error, that the upload is nil.
Here is the Rails part:
Picture-Model:
require 'paperclip'
class Picture < ActiveRecord::Base
# relations from picture
belongs_to :comic
belongs_to :user
has_many :picture_bubbles
has_many :bubbles, :through => :picture_bubbles
# attached file for picture upload -> with paperclip plugin
has_attached_file :file, :path => "public/system/pictures/:basename.:extension"
end
and the picture controller with the upload function:
class PicturesController < ApplicationController
protect_from_forgery :except => :upload
def upload
@picture = Picture.new(params[:picture])
@picture.position = params[:position]
@picture.comic_id = params[:comic_id]
@picture.url = params[:url]
@picture.user_id = params[:user_id]
if @picture.save
render(:nothing => true, :status => 200)
else
render(:nothing => true, :status => 500)
end
end
end
Does anyone know how to solve this problem?
thx,
tux