Previously, I posted on how I cropped and re-sized an image in Flex. Now, I will take you through some code snippets that I used to send the data over to .NET.
Flex:
I sent data to .NET using a UrlRequestLoader, again re-used code from some great person on the 'net.
public function saveFile(imageData:BitmapData):void{
// method accepts raw JPEG data as ByteArray as input
// create a URLRequest object pointed at the URL of the remote upload script
var request:URLRequest = new URLRequest(_uploadHandler+"?iKey="+_userId.toString());
// the call we will make is a standard HTTP POST call
request.method = "POST";
// this enables us to send binary data for the body of the HTTP POST call
request.contentType = "application/octet-stream";
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE,uploadPhotoHandler);
// the loader is the data being sent along to the server. Its dataFormat property lets us specify the format for the body, which, in our case, will be BINARY data
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
// the data property of our URLRequest object is the actual data being sent to the server, which in this case is the photo JPEG data
var myEncoder:JPEGEncoder = new JPEGEncoder(100);
var byteArray:ByteArray = myEncoder.encode(imageData);
request.data = byteArray;
urlLoader.load(request);
}
On the .NET side I had a handler setup to process this call. This part was easy to implement but took some digging to figure out all the right pieces.
It boiled down to getting the data out of the request using the BinaryReader. (actually I never knew that there was on attached to a Request). Then I used the File class to write out the image data.
.NET:
public void ProcessRequest(HttpContext context)
{
if (context.Request.TotalBytes > 0)
{
int userId = Convert.ToInt32(context.Request["iKey"]);
byte[] data = context.Request.BinaryRead(context.Request.TotalBytes);
string basePath =ConfigurationManager.AppSettings["Path"];
string uploadPath = context.Server.MapPath(basePath);
if (!System.IO.Directory.Exists(uploadPath))
System.IO.Directory.CreateDirectory(uploadPath);
if(data!=null)
{
string fileName = uploadPath + "xxx.jpg"));
File.WriteAllBytes(fileName, data);
}
}
}
Cool stuff. Out of curiosity why did you opt for Flash rather than Silverlight? Personally, I'm a flash fan, but I would expect that most .NET developers to opt for Silverlight since it uses C#.
ReplyDeleteah yes, Flash does seem out of place for me. Being so comfy with C#, I totally would have gone down the Silverlight road, but I'm not the project lead or imagine-neer :-) (And I'm totally okay with that, I would rather support than lead.)
ReplyDeleteIt is kind of fun learning new stuff. Flex/ActionScript3 has been quite interesting.
Although, I've wondered if I would be "happier" with Silverlight sometimes.