View Single Post
Old 07-27-2007, 08:41 AM   #4
luke_the_duke
New Member
 
Join Date: Jan 2006
Posts: 24
Default

Last but not least:
I found a way to upload a JPEG-encoded ByteArray without using AMFPHP. The method is really simple and works just as any normal multipart/form-data upload (FileReference Class, HTML etc.). As it consists of a normal "handmade" POST header, you can add additional POST variables to your request.
I was quite inspired by Pleh's posting, so many thanks. I also used the JPEGEncoder Class from bytearray.org.

The AS3 source code:
Code:
function sendJPG (bmpData: BitmapData): void {
	
	//Converting BitmapData into a JPEG-encoded ByteArray		
	var jpgObj: JPGEncoder = new JPGEncoder(100);
	var imageBytes: ByteArray = jpgObj.encode (bmpData);
	imageBytes.position = 0;
	
	var boundary: String = '---------------------------7d76d1b56035e';
	var header1: String  = '--'+boundary + '\r\n'
							+'Content-Disposition: form-data; name="Filename"\r\n\r\n'
							+'picture.jpg\r\n'
							+'--'+boundary + '\r\n'
							+'Content-Disposition: form-data; name="Filedata"; filename="picture.jpg"\r\n'
							+'Content-Type: application/octet-stream\r\n\r\n'
        //In a normal POST header, you'd find the image data here
	var header2: String =	'--'+boundary + '\r\n'
							+'Content-Disposition: form-data; name="Upload"\r\n\r\n'
							+'Submit Query\r\n'
							+'--'+boundary + '--';
	//Encoding the two string parts of the header
	var headerBytes1: ByteArray = new ByteArray();
	headerBytes1.writeMultiByte(header1, "ascii");
	
	var headerBytes2: ByteArray = new ByteArray();
	headerBytes2.writeMultiByte(header2, "ascii");
	
        //Creating one final ByteArray
	var sendBytes: ByteArray = new ByteArray();
	sendBytes.writeBytes(headerBytes1, 0, headerBytes1.length);
	sendBytes.writeBytes(imageBytes, 0, imageBytes.length);
	sendBytes.writeBytes(headerBytes2, 0, headerBytes2.length);
	
	var request: URLRequest = new URLRequest("http://www.yourdomain.ch/upload.php");
	request.data = sendBytes;
	request.method = URLRequestMethod.POST;
	request.contentType = "multipart/form-data; boundary=" + boundary;
	
	var loader:URLLoader = new URLLoader();
	loader.addEventListener(Event.COMPLETE, uploadCompleted);
	
	try {
		loader.load(request);
	} catch (error: Error) {
		trace("Unable to load requested document.");
	}
}

function uploadCompleted (e: Event) {
	trace(e.target.data)
}
I tested this code with the following PHP Script:
Code:
<?php

move_uploaded_file( $_FILES['Filedata']['tmp_name'], "testfolder/".md5($_FILES['Filedata']['tmp_name']).".jpg");

var_export($_FILES);
var_export($_POST);

?>

Last edited by luke_the_duke; 07-27-2007 at 09:00 AM.
luke_the_duke is offline   Reply With Quote