Save ByteArray to file with PHP

Just a short snippet of code to save a ByteArray into any file. I post this here because there is no good example on the web.

//-- your byte array you want to save
var bytes: ByteArray = new ByteArray();

//-- set up correct url request using post in binary mode
var request:URLRequest = new URLRequest ( 'http://pathto/save.php' );
var loader: URLLoader = new URLLoader();
request.contentType = 'application/octet-stream';
request.method = URLRequestMethod.POST;
request.data = bytes;
loader.load( request );

And of course you need a PHP file like this:

$fp = fopen( 'file.txt', 'wb' );
fwrite( $fp, $GLOBALS[ 'HTTP_RAW_POST_DATA' ] );
fclose( $fp );

52 Comments

  1. Posted May 15, 2006 at 1:01 pm | Permalink

    how we will go abt same when we need to implement it using asp or asp.net
    in this snippet i am confussed abt variables like
    bytes in request.data = bytes;
    where is data within bytes variable to write the file

    Thanks
    anil http://www.ade-technologies.com

  2. Posted May 16, 2006 at 2:03 pm | Permalink

    You have to fill the bytes variable with your file.
    And I have no clue about ASP(.NET).

  3. Michiel
    Posted Aug 15, 2007 at 5:23 pm | Permalink

    thanx, after 4 hours of reading AMFPHP manuals on Remote Objects in Flex 2, this was just the simple bit of script I needed. thanks a lot.

  4. Neil
    Posted Aug 18, 2007 at 10:45 pm | Permalink

    How would I go about retrieveing said ByteArray data from the server using amfphp and having Flash rebuild the BitmapData that was stored as a ByteArray? This would be for Flash CS3 using AS3. Is it even possible?

  5. Posted Aug 19, 2007 at 12:38 pm | Permalink

    AMFPHP can handle ByteArrays. So you can retrieve the ByteArray and put it into a Loader via loadBytes(). When the Loader is complete you can draw the Loader on a BitmapData. But honestly this does not make much sense. Why not load the file directly without AMFPHP?

  6. Neil
    Posted Aug 20, 2007 at 11:41 am | Permalink

    Well the file is being stored in the MySQL db right now. We had a semi working version earlier today. It worked only if the data wasn’t saved to the db. We tried something to see if it was indeed the data storage or if it was that the data wasn’t getting there properly. So we had php receive the data and then create a new bytearray from that data and send it back to flash and in that case we got the images drawing back. Once things got to the db tho it went sideways. We ended up going the Base64 route for today. We’re going to look at another way in the morning. The base64 added so much time and size to the files. About 33% larger and up to 4x slower for upload/download/processing. The reason we don’t just load the file with out the amfphp is that there is no file. All of the image data is stored as blobs in the db. I suppose we could rebuild the images on the server and then pass back urls as well. Maybe we’ll loook at that in the morning as well. If you’d like to talk about this more Joa I’d be more than happy to.

  7. smack
    Posted Dec 4, 2007 at 8:58 pm | Permalink

    it’s not really working for me.
    all I get is 0 sized files :( as if HTTP_RAW_POST_DATA isn’t there.
    can you post a working example?
    I am trying to save a test BitmapData object on the server, as a JPEG, and cannot use AMFPHP (the client refuses) and your solution seems to be the best, but it’s not working for me

    Thanks

  8. Roman
    Posted Feb 7, 2008 at 11:42 pm | Permalink

    That’s good. But is there any way to post it to $_FILES ? like a simple file upload because I want some more fields to be posted.

    Thanks!

  9. Posted Feb 8, 2008 at 12:09 am | Permalink

    Have a look at http://www.jooce.com/blog/?p=143

  10. Posted Feb 22, 2008 at 11:25 pm | Permalink

    This info is very good. Thanks for your works :)

  11. Posted May 1, 2008 at 4:29 am | Permalink

    Thanks for the help. I had everything except the PHP working. It seems so easy now. Big help.

  12. bubbleboy
    Posted Aug 24, 2008 at 12:52 pm | Permalink

    thanks! very useful!

  13. Posted Oct 22, 2008 at 12:05 pm | Permalink

    Here’s an ASP.net solution for saving/outputing the file.

    I also wanted to save the file (in this case a png) to the server so I’ve included this code too.

    Here’s how I solved the problem:

    Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs) Handles MyBase.Load

    ‘ Get the image file byte data from the HTTP request

    Dim fileData As Object
    fileData = Request.BinaryRead(Request.TotalBytes)

    ‘ Set the filename
    Dim strFileName As String = “yourFilename.png”

    ‘ Map the path to the relevant save folder
    Dim strPath As String = Server.MapPath(”files/”)
    strPath = strPath & strFileName

    ‘ write the file to disk
    Dim oFile As FileStream
    oFile = File.Create(strPath)
    oFile.Write(fileData, 0, Request.TotalBytes)
    oFile.Close()

    ‘ push the file to the user
    Response.AddHeader(”Content-Disposition”, “attachment; filename=” & strFileName)
    Response.AddHeader(”Content-Type”, “image/png”)
    Response.ContentType = “application/octet-stream”
    Response.BinaryWrite(fileData)

    End Sub

    You’ll need to import System.IO in your ASPX file and the IUSR account will need write permission to the folder where you want to save the image.

    Hope this helps the non-PHPers!

  14. Anthony
    Posted Nov 5, 2008 at 8:41 pm | Permalink

    I was able to succesfully get a graphics image up to the server using php however i would like to have a dynamic filename. How would I go about doing that?

  15. RavenWorks
    Posted Mar 14, 2009 at 5:37 pm | Permalink

    Oh man, perfect :) Every example I could find was some giant complicated thing — I knew there had to be a simpler way of doing it. This is exactly what I needed, thank you. :)

  16. Posted Jun 12, 2009 at 5:57 am | Permalink

    thank you.

  17. Posted Jun 15, 2009 at 8:32 pm | Permalink

    it really helped.
    i used this method for saving pictures from flash.
    in this page.
    http://www.ezzal.com/sketch.html

    good luck..

    - Dharshan

  18. binds
    Posted Jun 19, 2009 at 10:04 am | Permalink

    How would I go about sending and retrieveing said ByteArray data from the server using php and having Flash rebuild the BitmapData that was stored as a ByteArray? This would be for Flash CS3 using AS3. Is it even possible?

    Please help me . i have triad ur example it receive data but how to reuse that data from server to rebuild the BitmapData

  19. binds
    Posted Jun 19, 2009 at 3:35 pm | Permalink

    Hi!

    I trying to find a flash based draw app solution for an
    intranet with save to server capability with no luck.

    Anyone can help point to such an app. Requirements:

    2) basic drawing, colors and text
    3) ability to load from server
    4) ability to save to server ( jpg, gif, or whatever )

  20. Posted Jun 19, 2009 at 3:36 pm | Permalink

    Why not just use a Loader in that case? Or is your image uncompresed and not a PNG/JPEG? This would be a really bad idea.

  21. bins
    Posted Jun 20, 2009 at 6:50 am | Permalink

    thanx, But plz can u share the code with me how to implement this. i have to save drawing api to server and then reuse it from server to flash

  22. saurabh
    Posted Jun 25, 2009 at 9:05 am | Permalink

    How to retrieve byteArray from server to redraw it on FLASH canvass in AS3.0 and PhP??

  23. Posted Jun 25, 2009 at 12:11 pm | Permalink

    Loader.load() if it is a PNG/JPEG.

  24. shivendra
    Posted Jun 25, 2009 at 2:57 pm | Permalink

    can u tell how to retrive byte array from server to redarw image on flash , i dont want to load jpeg directly i want to redraw that image by bytearray

  25. Mick
    Posted Aug 28, 2009 at 10:18 am | Permalink

    How do you echo a “success” from PHP, then have the Flash trigger an onComplete handler so we can have the flash post to the PHP file, then listen for a success.

  26. Posted Oct 28, 2009 at 2:15 am | Permalink

    wow finally a simple PHP example for us flash/flex heads.

    THANKS

    -sean http://www.onegiantemedia.com

  27. Paul
    Posted Nov 11, 2009 at 2:14 pm | Permalink

    Hi, Thanks for the example. Does anyone have any idea how to do this with JSP. I have never looked as JSP before today.

    Any help much appreciated.

  28. Foz
    Posted Dec 5, 2009 at 5:00 pm | Permalink

    how would i use this with the jpeg encoder to save the resulting saved image to a folder?

  29. Yessica
    Posted Feb 6, 2010 at 10:08 pm | Permalink

    you cant imagine how this has helped me, thank you!!!!

  30. Posted Mar 22, 2010 at 7:12 am | Permalink

    Wow! Thank you so much for this code. i have been playing around for hours and gotten nowhere, this code was exactly what I needed.

    http://www.joshuacrigger.com/

  31. Saqib Ahmad
    Posted Apr 13, 2010 at 1:30 pm | Permalink

    Thanks a lot bro, its really great small post i am now working on large files upload in chunks and that all is based on your small piece of code. thanks you really help!

    i will publish my code when its done.

  32. Piet
    Posted May 12, 2010 at 5:39 pm | Permalink

    I’ve a question about the security of this method.

    There is no security, right?

    Everybody can send a request to the requestUrl and insert chars in the file specified or am I wrong?

  33. Kannan
    Posted May 28, 2010 at 2:47 am | Permalink

    Why its creating 0 byte file?

  34. Nik
    Posted Jul 7, 2010 at 3:41 pm | Permalink

    Great snippet thanks!
    I’m looking for a way to pass the file name of the newly created image back to Flash so I can write the url to a database.

    I’ve been trying to get the value from contentLoaderInfo but I don’t think that property is available…

  35. Posted Aug 25, 2010 at 5:08 am | Permalink

    Thanks a lot. I lost hours because I was not setting
    request.contentType = ‘application/octet-stream’;

  36. Posted Aug 30, 2010 at 10:15 pm | Permalink

    Greate example!
    Grazie ;)

  37. Aldo Marsilio
    Posted Nov 1, 2010 at 12:57 pm | Permalink

    Absolutely awesome job.
    Is there a way to have a progress bar indicator while we send the bytearray to PHP? I would like to give to the users an indication on about how long they have to wait in order to have that snapshot saved onto the server.

  38. Posted Nov 29, 2010 at 4:29 pm | Permalink

    Perfect, thanks a lot – just what I was looking for!

  39. Posted Nov 29, 2010 at 4:30 pm | Permalink

    Works a treat, thanks.

  40. tom
    Posted Feb 24, 2011 at 3:32 pm | Permalink

    hey thanks for that snippet!
    is it possible to send the ByteArray directly as an image email attachment?
    any ideas on that?

  41. Posted Mar 10, 2011 at 7:55 pm | Permalink

    Once again thank you soo much! This code has rocked. I finally finished my project and if it was not for you code I would have been stuck for another week +.

    You can check out what I created with it at the following link. http://www.runlikeananimal.com/postcard.html

    The way I used the code was to save the bytearray as a .jpg file onto our server so that users can either directly download the postcard they made, email it, or even post it to a social network.

    http://www.joshuacrigger.com/

  42. Jipe
    Posted Apr 7, 2011 at 7:36 pm | Permalink

    If it’s creating empty files, check folder permissions. After two hours of searching, tried to give the folder chmod777 and it works!! Thanks!

  43. GJ
    Posted Jul 23, 2011 at 1:54 am | Permalink

    I have been able to save a file named file.txt to my server. It has a bunch of grabley characters in it and is 74K. What do I do with this to see it as an uploaded image? This is all new and exciting. So close but yet far.

    Thanks!

  44. Sathyan
    Posted Dec 14, 2011 at 8:17 pm | Permalink

    Can any one tell me the location of the saved file file.txt in the website or localhost after using the php code

    $fp = fopen( ‘file.txt’, ‘wb’ );
    fwrite( $fp, $GLOBALS[ 'HTTP_RAW_POST_DATA' ] );
    fclose( $fp );

    Thanks in Advance

  45. Posted Dec 19, 2011 at 12:54 pm | Permalink

    Hello,

    I had problem with your script and php mod security:

    ModSecurity: Multipart parsing error: Multipart: Invalid Content-Disposition header (-12): form-data; name=”image_file”;
    filename=”screenshot.jpg”screenshot.jpg”

    The problem is with the filename duplication: screenshot.jpg”screenshot.jpg

    Solution:
    bytes = ‘Content-Disposition: form-data; name=”‘+uploadDataFieldName+’”; filename=”‘ + fileName + ”; // removed quote from and of line between ”
    And I had to comment out this line:
    //postData.writeUTFBytes(fileName);

    Is it a proper solution? What you think?

    Best,
    Andrew

  46. Posted Dec 19, 2011 at 1:08 pm | Permalink

    Sorry, this post was intented to sent here:)
    http://marstonstudio.com/2007/10/19/how-to-take-a-snapshot-of-a-flash-movie-and-automatically-upload-the-jpg-to-a-server-in-three-easy-steps/
    Just you were on the credit list.
    I had a long weekend..

    A.

  47. Eduardo
    Posted Feb 5, 2012 at 11:26 pm | Permalink

    Thanks a lot man, every other $·%· site was publishing a lot of long crap. Your example is short but to the point. Worked on the first try THANKS!

  48. Matt
    Posted Mar 8, 2012 at 7:29 pm | Permalink

    Im attempting to use your code – but I must not understand. I am getting a byte array back from a WCF service, and getting the array from a POST. Code is below:

    $idPDF, “username” => $userPDF, “password” => $passPDF);
    $data_string = json_encode($data);
    $ch = curl_init(‘http://*****.com/***/DealPdf’);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, “POST”);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_VERBOSE, 1 );
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    ‘Content-Type: application/json’)
    );
    $result = curl_exec($ch);
    ?>

    If I understand correctly, the “$result” is the byte array. But I dont know how to get it out of the byte array and save it as a PDF. Using your example, It isnt working. What am I missing?

  49. joana
    Posted Mar 17, 2012 at 10:17 am | Permalink

    can you please send me the .fla and th php. i badly need it..
    i want my image to be save directly on the database and not in the desktop.. how will i do this.. Waiting for your reply. Thanks

  50. Posted Jun 7, 2012 at 8:11 am | Permalink

    oohhh yeah! Thanks, 3 days but you save me.

  51. Posted Jul 9, 2012 at 10:26 am | Permalink

    If I read from file system. and overwrite again. This solution does still work?

  52. Maria Lopez
    Posted Nov 12, 2012 at 2:27 pm | Permalink

    Works like a charm, thanks!

3 Trackbacks

  1. By Jooce Blog » Real file upload with AS3 on Jun 4, 2007 at 12:24 pm

    [...] which is just dumping the file in the post header and making use of the raw HTTP post data. I wrote an article about this while [...]

  2. [...] Save ByteArray to file with PHP at blog.je2050.de – blog and database of joa ebert [...]

  3. By DClick Blog on Nov 6, 2007 at 7:36 pm

    [...] Feito isso a parte Java fica fcil. No blog do Jonathan Marston voc encontra um exemplo de como fazer a mesma coisa com PHP. [...]