How can I send another variable with FileReference Upload? - apache-flex

I have a problem with the filereference class using the upload function.
I want to send the folderLocation variable with fileReference.upload().
Below I try to describe my strategy.
var folderLocation : String = "photos/myUniqueFolder/";
private var serverSideScript:String = "http://localhost/project/phpFlexMechanism/upload.php";
urlRequest = new URLRequest(serverSideScript);
fileReferenceList.addEventListener(Event.SELECT, fileSelectedHandler);
private function fileSelectedHandler(event:Event):void {
// upload the file to the server side script
fileReference.addEventListener(Event.COMPLETE, uploadCompleteHandler);
fileReference.upload(urlRequest);
}
In PHP I use this to get the the file and uploaded
$folder = $_POST['folder'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$fileName = $_FILES['Filedata']['name'];
$fileSize = $_FILES['Filedata']['size'];
move_uploaded_file($tempFile, "../user/$folder/uploadImages/" . $fileName);
But how can I send the folder through the "upload reference"?

I would think that, since you FileReference needs a URLRequest, you would be able to piggy back that information through the URLRequest itself by using the flash.net.URLVariables object.
I've not had time to test this, but have you tried:
// put this right after you instantiate urlRequest;
var urlVars:URLVariables = new URLVariables();
urlVars.targetFolder = folderLocation;
urlRequest.method = "post";
urlRequest.data = urlVar;
That should let you do:
//replace your last line with these two.
$folder = $_REQUEST[ "targetFolder" ];
move_uploaded_file($tempFile, "../user/$folder/uploadImages/" . $fileName);
in PHP.

the easiest thing you can do is just send it through with a get header in the upload function
so the code looks as follows
private var serverSideScript:String = "http://localhost/project/phpFlexMechanism/upload.php?extraVar=value&extraVarB=value2";
fileReference.upload(urlRequest);
then in the php script you just use
$_GET['extraValue']
$_GET['valueVarB']

Related

Convert .Net example to PowerShell

I have a project to write a script that connects to a Web Service and retrieve information of selected records. Unfortunately there is no PowerShell support from the vendor. Their documents only provides .Net examples. The web service that I am trying to retrieve information is for HP Trim v7. Maybe some of you are familiar.
Here is the .Net example from vendor
Example – Title Word search
// Construct a request object
TrimRequest request = new TrimRequest();
// Construct a RecordStringSearchClause, with type
// TitleWord, and argument "reef"
RecordStringSearchClause clause = new RecordStringSearchClause();
clause.Type = RecordStringSearchClauseType.TitleWord;
clause.Arg = "reef";
// Construct a record search, and put our search clause in it
RecordSearch search = new RecordSearch();
search.Items = new RecordClause[] { clause };
// Put our search operation into our TrimRequest
request.Items = new Operation[] { search };
// Send it off. Whatever comes back will be in response
Engine engine = new Engine();
engine.Credentials = new System.Net.NetworkCredential(username, password);
TrimResponse response = engine.Execute(request);
And here is my PowerShell code
$url = "http://localhost/trimws/trim.asmx"
$Engine = New-WebServiceProxy -Uri $url -Class "proxy" -Namespace "Connection" -UseDefaultCredential
$RecordStringSearchClause = New-Object Connection.RecordStringSearchClause
$ClauseType = New-Object Connection.RecordStringSearchClauseType
$ClauseType.value__ = 4 ##Record Number
$RecordStringSearchClause.Type = $ClauseType
$RecordStringSearchClause.Arg = "39299763"
$RecordSearch = New-Object Connection.RecordSearch
$RecordClause = New-Object Connection.RecordClause ## doesn't work
$RecordSearch.Items = New-Object Connection.RecordClause { $RecordStringSearchClause } ## doesn't work
$RecordSearch.Items = $RecordStringSearchClause
$TrimRequest = New-Object Connection.TrimRequest
$TrimRequest.Items = $RecordSearch
$Engine.Execute($TrimRequest) ## returns nothing
Could any body help me to convert above .Net code into PowerShell script? (if technically possible)

Mocking a GuzzleHttp response

How should I mock a Guzzle response properly. When testing a parser I'm writing, the test html is contained in files. In my PHPUnit tests I'm doing file_read_contents and passing the result into my method. Occasionally the HTML will link to a seperate file. I can mock this response like so:
public function testAlgo()
{
$mock = new MockAdapter(function() {
$mockhtml = file_get_contents($this->dir . '/HTML/authorship-test-cases/h-card_with_u-url_that_is_also_rel-me.html');
$stream = Stream\create($mockhtml);
return new Response(200, array(), $stream);
});
$html = file_get_contents($this->dir . '/HTML/authorship-test-cases/h-entry_with_rel-author_pointing_to_h-card_with_u-url_that_is_also_rel-me.html');
$parser = new Parser();
$parser->parse($html, $adaptor = $mock);
Then in my actual method, when I make the guzzle request this code works:
try {
if($adapter) {
$guzzle = new \GuzzleHttp\Client(['adapter' => $adapter]);
} else {
$guzzle = new \GuzzleHttp\Client();
}
$response = $guzzle->get($authorPage);
So obviously this isn't ideal. Does anyone know of a better way of doing this?
$html = (string) $response->getBody();
EDIT: I'm now using the __construct() methid to set up a default Guzzle Client. Then a using a second function that can be called by tests to replace the Client with a new Client that has the mock adapter. I'm not sure if this is the best way to do things.
You can use the MockPlugin API, like so:
$plugin = new MockPlugin();
$plugin->addResponse(__DIR__.'/twitter_200_response.txt');
The txt file then contains everything from your response, including headers.
There are also good approaches available here: http://www.sitepoint.com/unit-testing-guzzlephp/
Also there are articles found here: http://guzzle3.readthedocs.io/testing/unit-testing.html

how to send byte array to server in flash builder (Flex 4)

I have a video file in my local system.I am using windows XP in my system. Now i want to send this video file byte array to server in Flash Builder (Flex 4). I am using PHP at server end.
How can i do this? Please guide
Thanks
Socket.writeBytes() will do what you need.
Via this link:
.
// serialization
var serializedSound:ByteArray;
serializedSound = serializeSound(sound);
serializedSound.position = 0;
// unserialization
var newSound:Sound = new Sound();
newSound.addEventListener(SampleDataEvent.SAMPLE_DATA, deserialize);
newSound.play();
function serializeSound(sound:Sound):ByteArray
{
var result:ByteArray = new ByteArray();
while( sound.extract(result, 8192) ){
result.position = result.length;
}
return result;
}
function deserialize(e:SampleDataEvent):void
{
for ( var c:int=0; c<8192; c++ ) {
if(serializedSound.bytesAvailable < 2) break;
e.data.writeFloat(serializedSound.readFloat());
e.data.writeFloat(serializedSound.readFloat());
}
}
Do you need just sending the bytearray to PHP or also getting the bytearray?
For sending the bytearray you can use Zend_AMF:
http://framework.zend.com/download/amf
It will handle all the conversion, and in php you will get the bytearray as a string through a variable (I use variable reference as: &$file to save some memory on calling of method)
Here is some code snippet it can help you:
Sending ByteArray to Zend_Amf
For getting the ByteArray you can use the FileReference load() method to get all the bytearray of a local file.
You do know that creating a ByteArray of the video in Flex is literally storing that video to memory right? Any kind of large or uncompressed video would use an enormous amount of client side memory which could cause errors if Flash hits its memory limit.
I don't think you're going about this the right way. What I recommend you do is instead just upload the video to the server which the server than then access the bytes within it. If you want to upload the video to the server, look at this tutorial here which shows how to upload the file from Flex and a PHP script to get and store the file: http://livedocs.adobe.com/flex/3/html/17_Networking_and_communications_7.html#118972
From here, PHP could then access the bytes if you are so inclined.
AS3 Code:
uploadURL = new URLRequest();
uploadURL.url = "upload.php?fileName=videotrack";
uploadURL.contentType = 'application/octet-stream';
uploadURL.method = URLRequestMethod.POST;
uploadURL.data = rawBytes;
urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
urlLoader.load(uploadURL);
rawBytes is the byte array that you want to upload to the server.
PHP Code
$fileName = $_REQUEST['fileName'] . ".mp3";
$fp = fopen( $fileName, 'wb' );
fwrite( $fp, $GLOBALS[ 'HTTP_RAW_POST_DATA' ] );
fclose( $fp );
I've used a .mp3 extension because my byte array was data from a mp3 file, but you can set the extension to whatever type of file your byte array represents.

Adobe AIR/Flex file upload to a server that requires basic authentication

Adobe reference specifically points this out as a limitation.
Here's the note in the file.upload functionality in adobe reference.
Note: If your server requires user authentication, only SWF files running in a browser — that is, using the browser plug-in or ActiveX control — can provide a dialog box to prompt the user for a username and password for authentication, and only for downloads. For uploads using the plug-in or ActiveX control, or for uploads and downloads using the stand-alone or external player, the file transfer fails.
click here for the full reference page for File
Has anyone been able to work around this limitation. One thought I had was to use the native support in AIR for Javascript and see that works. Anyone tried that? Anyone have other ideas?
I've also tried the solution proposed here and it didn't work. According to the questioner in the forum it didn't seem to work for him either. Probably hitting the issue/limitation mentioned above.
I understand how to include basic authentication on a URLRequest and that works fine for me if I'm posting key/value pairs. But when I attempt to upload a file it does not work. It just sits there and does not fire any of the file.upload events. No errors no progress. Any help is much appreciated.
Here's my sample code:
var sendVars:URLVariables = new URLVariables();
sendVars.prop1 = "filename" ;
var urlRequest:URLRequest = new URLRequest();
urlRequest.method = URLRequestMethod.POST ;
urlRequest.data = sendVars ;
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode("user:pass");
var credsHeader:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + encoder.toString());
urlRequest.requestHeaders.push(credsHeader);
file = new File(url);
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA , file_UploadCompleteDataHandler );
file.addEventListener( Event.OPEN, fileOpenHandler);
file.addEventListener(ProgressEvent.PROGRESS, fileProgressHandler);
file.addEventListener(Event.COMPLETE, file_CompleteHandler);
file.addEventListener(IOErrorEvent.IO_ERROR, file_IOErrorHandler);
file.addEventListener(HTTPStatusEvent.HTTP_STATUS , file_HTTPStatusHandler);
file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, file_SecurityErrorHandler);
try {
// Start the file upload
file.upload(urlRequest, "primaryFile", false);
}
catch (error:Error) {
trace( "Unable to upload file." + file.name);
}
Do exactly what you are doing except get the file.data and pass it into this....
public static function prepareWithFormData(vars:MetadataList, bytes:ByteArray, fieldName:String, filename:String, request:URLRequest):void {
bytes.position = 0;
var boundary: String = '---------------------------' + UIDUtil.createUID();
var header1: String = "";
var varsArray:Array = vars.asArray();
for each(var item:Metadata in varsArray) {
header1 += "\r\n--" + boundary + "\r\n";
header1 += 'Content-Disposition: form-data; name="' + item.name + '"\r\n\r\n';
header1 += item.value;
}
header1 += '\r\n--'+boundary + '\r\n'
+'Content-Disposition: form-data; name="' + fieldName + '"; filename="'+filename+'"\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 = '\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(bytes, 0, bytes.length);
sendBytes.writeBytes(headerBytes2, 0, headerBytes2.length);
request.data = sendBytes;
request.method = URLRequestMethod.POST;
request.contentType = "multipart/form-data; boundary=" + boundary;
}

FileReference and HttpService Browse Image Modify it then Upload it

I am trying to do an image uploader, user can:
- browse local file with button.browse
- select one and save it as a FileReference.
- then we do FileReference.load() then bind the data to our image control.
- after we make a rotation on it and change the data of image.
- and to finish we upload it to a server.
To change the data of image i get the matrix of the displayed image and transform it then i re-use the new matrix and bind it to my old image:
private function TurnImage():void
{
//Turn it
var m:Matrix = _img.transform.matrix;
rotateImage(m);
_img.transform.matrix = m;
}
Now the mater is that i really don't know how to send the data as a file to my server cause its not stored in the FileReference and data inside FileReference is readOnly so we can't change it or create a new, so i can't use .upload();.
Then i tried HttpService.send but i can't figure out how you send a file and not a mxml.
You can use URLLoader to send Binary ByteArray to server, like:
var urlRequest : URLRequest = new URLRequest();
urlRequest.url = 'path to your server';
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = UploadPostHelper.getPostData( 'image.jpg', byteArray );
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
// create the image loader & send the image to the server:<br />
var urlLoader : URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.load( urlRequest );
First get bitmapdata for the image:
// set up a new bitmapdata object that matches the dimensions of the captureContainer;
var bmd : BitmapData = new BitmapData( captureContainer.width, captureContainer.height, true, 0xFFFFFFFF );
// draw the bitmapData from the captureContainer to the bitmapData object:<br />
bmd.draw( captureContainer, new Matrix(), null, null, null, true );
Then get byteArray:
var byteArray : ByteArray = new JPGEncoder( 90 ).encode( bmd );
and use the above URLLoader code to send image to server.
It will work fine, except you wouldn't get the file upload progress like the one you get from FileReference.upload. If you can make upload progress work using URLLoader, please post your answer here.

Resources