views:

29

answers:

2

I want to upload a file(photo) from Flex to Rails and then send a response back to the server in XML (contains photo URL and ID). I'm sending from my Rails server some XML as follows:

render(:xml => {:id => @photo.id, 
                :photoURL => @photo.URL, 
                :thumbPhotoURL => @photo.thumbURL})

This is sent through FileReference object through fileReference.upload()

I try to render it in the complete handler:

fileReference.addEventListener(Event.COMPLETE,function(event:Event):void {
                    var xml:XML = new XML(event.target.data);
                    ......

it doesn't seem to parse XML properly. I have used similar code before with URLLoader and it worked. Any ideas?

+1  A: 

FileReference is for transferring files between user's hard disk and the server - the upload() function is for sending a file from user's machine to the server.

Use URLLoader to load xml from the server to your flex application

var ldr:URLLoader = new URLLoader();
ldr.addEventListener(Event.COMPLETE, onLoad);
ldr.load(new URLRequest(url));

function onLoad(e:Event):void
{
  var loadedText:String = URLLoader(e.target).data;
  trace(loadedText);
  var xml:XML = new XML(loadedText);
  trace(xml.toXMLString());
}
Amarghosh
Thanks @Amarghosh I'm using fileReference.load() because of convenience in loading file to server. I have done this with URLLoader but it's more work as I have to convert the file manually to bytearray. Can I easily upload file with URLLoader? otherwise I don't understand why I don't get proper XML when I use fileReference it print out gibberish
Tam
+1  A: 

Hi Tam

May i ask why you're converting the data to a ByteArray? URLLoader actually has a great property called dataFormat which you can use to specify the way that Flash will handle the loading. You can choose between binary, text or url-encoded variables.

Like Amarghosh said, you're probably better off using the URLLoader for working with XML.

Danny Kopping
Actually you are right, parsing XML back worked with URLLoader. I need to convert my data to bytearray because I want to upload an image (jpeg/gif/png) to the server. I'm not sure how to upload a file with URLLoader without converting it to a bytearray. Do you have an example for uploading files in URLLoader?
Tam
Ah, i see.. Now it's a little more clear what your problem is. To be honest, when uploading an image, i'd rather convert it to base-64 data and then upload that. You'll be able to upload a raw image file rather easily with FileReference (see http://stackoverflow.com/questions/762226/how-to-upload-a-bitmapdata-object-straight-to-my-server for reference), but if you don't want to use a bytearray then you'll probably be able to use this exact same method.
Danny Kopping