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

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.

Related

Video Playing From Memory Stream

I am working in asp.net c#. I want to play video from memory stream. I am encrypting and decrypting video. I am storing the decrypted video in memory stream, and want to play it, without saving. I have googled it and found number of post, but mostly the post are uncompleted or provided the link with directshow. I have also tried with directshow, but it's totally new for me and contains number of demos, that made a confusion which one to use for Memory stream.
I just want to play decrypted video data from memory stream . Please let me know what I can do, it will be more good if there is a sample available from any forums.
My decrypted code
public bool DecryptData(String inName, String outName, byte[] rijnKey, byte[] rijnIV)
{
FileStream fin = null;
FileStream fout = null;
CryptoStream decStream = null;
try
{
fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
//Create variables to help with read and write.
byte[] bin = new byte[bufLen]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.
RijndaelManaged rijn = new RijndaelManaged();
//DES ds = new DESCryptoServiceProvider();
decStream = new CryptoStream(fin, rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Read);
//odkoduj testowy fragment
byte[] test = new byte[testHeader.Length];
decStream.Read(test, 0, testHeader.Length);
string contents = new StreamReader(decStream).ReadToEnd();
byte[] unicodes = Encoding.Unicode.GetBytes(contents);
MemoryStream msOutput = new MemoryStream(unicodes);
//here I have to implement player that plays from memory stream.
}
catch
{}
}
I have answered one question regarding encrypting and decryption of a video file but i can understand you don't want to save a physical copy of that file on client machine.
https://stackoverflow.com/a/58129727/9869635
But it is not possible to play a video file from memorystream (not sure about some paid third party tools)
so one way you can do it like below approach:
1: Save that file in client's "temp" folder e.g. "temp/myvideos/sample.mkv"
2: Make it hidden from properties (How to hide file in C#?)
3: Play the video from there
4: once it is played, delete all files from that custom folder from "temp" folder (myvideos).
The best way to do it today, that works for any platform... is to use Http Live Streaming and then you can either use a player that supports HLS or you can simply use the HTML5 video tag. See my updated answer below...
Play a video without a file on disk [Java]

Cannot upload large (>50MB) files to SharePoint 2010 document library

I'm trying to upload a large file to a document library, but it fails after just a few seconds. The upload single document fails silently, upload multiple just shows a failed message. I've turned up the file size limit on the web application to 500MB, and the IIS request length to the same (from this blog), and increased the IIS timeout for good measure. Are there any other size caps that I've missed?
Update I've tried a few files of various sizes, anything 50MB or over fails, so I assume something somewhere is still set to the webapp default.
Update 2 Just tried uploading using the following powershell:
$web = Get-SPWeb http://{site address}
$folder = $web.GetFolder("Site Documents")
$file = Get-Item "C:\mydoc.txt" // ~ 150MB
$folder.Files.Add("SiteDocuments/mydoc.txt", $file.OpenRead(), $false)
and get this exception:
Exception calling "Add" with "3" argument(s): "<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file with URL 'http://{site address}/SiteDocuments/mydoc.txt' in this Web."
which strikes me as odd as of course the file wouldn't exist until it's been uploaded? N.B. while the document library has the name Site Documents, it has the URL SiteDocuments. Not sure why...
Are you sure you updated the right webapp? Is the filetype blocked by the server? Is there adequate space in your content database? I would check ULS logs after that and see if there is another error since it seems you hit the 3 spots you would need too update.
for uploading a large file, you can use the PUT method instead of using the other ways to upload a document.
by using a put method you will save the file into content database directly. see the example below
Note: the disadvantage of the code below is you cannot catch the object that is responsible for uploading directly, on other word, you cannot update the additional custom properties of the uploaded document directly.
public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)
{
//Flag to indicate whether file was uploaded successfuly or not
bool isUploaded = true;
try
{
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
//Set credentials of the current security context
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = “PUT”;
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
{
//Get the start point
int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
// Perform the PUT request
WebResponse response = request.GetResponse();
//Close response
response.Close();
}
catch (Exception ex)
{
//Set the flag to indiacte failure in uploading
isUploaded = false;
}
//Return the final upload status
return isUploaded;
}
and here are an example of calling this method
UploadFileToDocumentLibrary(#”C:\test.txt”, #”http://home-vs/Shared Documents/textfile.pdf”);

Adobe AIR. Local network error

For example, in local network, when Adobe Air is reading files from local server (\\Server\storage\) and network will be in down for a second, Air becomes eat a lot of memory and it is increasing up to 1GB (while normal memory use is 100 kb or less).
Just reading file with File('file path on local server'); from unstable network can cause this error.
Have anybody seen that in projects?
private function init() : void
{
file = new File("\\Server\dragracing\results.txt");
fileStream = new FileStream();
fileStream.addEventListener( Event.COMPLETE, fileComplete );
fileStream.openAsync( file, FileMode.READ );
}
private function fileComplete( event : Event ):void
{
fileContents = fileStream.readMultiByte( fileStream.bytesAvailable, ISO_CS );
.....
}
]]>
Have you tried closing the FileStream in the fileComplete method? Call the close method to make that happen.
private function fileComplete( event : Event ):void
{
fileContents = fileStream.readMultiByte( fileStream.bytesAvailable, ISO_CS );
fileStream.close();
.....
}
Also, based on your code it does not appear that you are ever actually reading information in from the file. from the file; so it is not clear the complete method will ever execute. There are plenty of methods used to read information in using the FileStream class.

Saving a bytearray with php received from Flex Air app

I have an Air application with remote service in codeigniter.
I'm trying to save a bytearray that I received from the Air app
but when I save the data I get empty files with the correct filename.
So there must be something wrong with my bytearray or the way I save the data.
Does anyone have an idea what I'm doing wrong?
I've debugged the Arraycollection I sent and the bytearray is definitely in there.
public function uploadImage($image)
{
foreach($image as $img)
{
$file = $img['name'];
$data = new ByteArray($img['bytes']);
file_put_contents( $_SERVER['DOCUMENT_ROOT'] . '/uploads/test/' .$file, $data);
}
}
Ok for those who are interested in the solution, aparrently I just had to change this $data = new ByteArray($img['bytes']); into this $data = $img['bytes’]->data;

How can you save out a String into a file in AS3?

I have a string the user has typed and I want to save it into a file on the users harddrive. Can you do that? And if so, how?
Yes you can, with FileReference.
This is basically how it's done:
var bytes:ByteArray = new ByteArray();
var fileRef:FileReference=new FileReference();
fileRef.save("fileContent", "fileName");
Doesn't look too hard, does it?
And here's a video-tutorial on it too:
http://www.gotoandlearn.com/play?id=76
And the documentation:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/
Hope that helps.
Since I had a function to output bytes to a file (because I was doing something with bitmaps), I reused it to output a string as well, like this:
var filename:String = "/Users/me/path/to/file.txt";
var byteArray:ByteArray = new ByteArray();
byteArray.writeUTFBytes(someString);
outFile(filename, byteArray);
private static function outFile(fileName:String, data:ByteArray):void {
var outFile:File = File.desktopDirectory; // dest folder is desktop
outFile = outFile.resolvePath(fileName); // name of file to write
var outStream:FileStream = new FileStream();
// open output file stream in WRITE mode
outStream.open(outFile, FileMode.WRITE);
// write out the file
outStream.writeBytes(data, 0, data.length);
// close it
outStream.close();
}
In addition, you must have Flash Player 10 and a Flex Gumbo SDK installed in your Flex Builder 3.
You can also have a look the following example:
http://blog.flexexamples.com/2008/08/25/saving-files-locally-using-the-filereference-classs-save-method-in-flash-player-10/
In Flex 3 no you can't do it unless you upload the file to the server and then download the file via a url to the desktop.
In Air or Flex 4 you can save it directly from the application to the desktop as detailed above.

Resources