I'm using html5 canvas to capture a signature and store it in MySQL. I've got everything in the script working except for the part that saves the signature and sends it to MySQL.
My knowledge of AJAX is none so I'm working off what I read in books, see on tutorials and get help on from here.
So in Firefox console when I click on save signature I can see the script displays the post.php file it's supposed to go to and displays a 200 ok notification but nothing happens, it doesn't post in MySQL (which doesn't surprise me as I'm sure my code is incorrect) and I don't see any errors.
What I want to accomplish is to upload the signature image to a folder on the server and save the path to the image in MySQL. Being unfamiliar with JavaScript, Jquery and Ajax I'm confused with how to get this to function.
Here is the jquery:
$(document).ready(function () {
/** Set Canvas Size **/
var canvasWidth = 400;
var canvasHeight = 75;
/** IE SUPPORT **/
var canvasDiv = document.getElementById('signaturePad');
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if (typeof G_vmlCanvasManager != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
}
var context = canvas.getContext("2d");
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
/** Redraw the Canvas **/
function redraw() {
canvas.width = canvas.width; // Clears the canvas
context.strokeStyle = "#000000";
context.lineJoin = "miter";
context.lineWidth = 2;
for (var i = 0; i < clickX.length; i++) {
context.beginPath();
if (clickDrag[i] && i) {
context.moveTo(clickX[i - 1], clickY[i - 1]);
} else {
context.moveTo(clickX[i] - 1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke();
}
}
/** Save Canvas **/
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
$("#imgData").html('Thank you! Your signature was saved');
var ajax = XMLHttpRequest();
ajax.open("POST", 'post.php');
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(sigData);
// $('#debug').html(sigData);
});
/** Clear Canvas **/
$('#clearSig').click(
function clearSig() {
clickX = new Array();
clickY = new Array();
clickDrag = new Array();
context.clearRect(0, 0, canvas.width, canvas.height);
});
/**Draw when moving over Canvas **/
$('#signaturePad').mousemove(function (e) {
if (paint) {
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
/**Stop Drawing on Mouseup **/
$('#signaturePad').mouseup(function (e) {
paint = false;
});
/** Starting a Click **/
function addClick(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
$('#signaturePad').mousedown(function (e) {
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
});
and here is the PHP: Also I didn't write the php code below it's part of the entire signature pad so I'm sure it's not correct.
<?php
session_start();
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$session_id = $_SERVER['REMOTE_ADDR'];
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
$imageName = "sign_" . rand(5,1000) . rand(1, 10) . rand(10000, 150000) . rand(1500, 100000000) . ".png";
//Set the absolute path to your folder (i.e. /usr/home/your-domain/your-folder/
$filepath = "xampp/htdocs/alpha/site7/images/" . $imageName;
$fp = fopen("$filepath", 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
//Connect to a mySQL database and store the user's information so you can link to it later
$link = mysql_connect('localhost','root', 'password') OR DIE(mysql_error);
mysql_select_db("customer", $link);
mysql_query("INSERT INTO 'signature' ('session', 'image_location') VALUES ('$session_id', '$imageName')") OR DIE(mysql_error());
mysql_close($link);
}
?>
And the html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Signature Pad</title>
<!-- The Signature Pad -->
<script type ="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="signature-pad.js"></script>
</head>
<body>
<center>
<fieldset style="width: 435px">
<br/>
<br/>
<div id="signaturePad" style="border: 1px solid #ccc; height: 55px; width: 400px;"></div>
<br/>
<button id="clearSig" type="button">Clear Signature</button>
<button id="saveSig" type="button">Save Signature</button>
<div id="imgData"></div>
<div
<br/>
<br/>
</fieldset>
</center>
<div id="debug"></div>
</body>
</html>
After some head beating over this I've finally been able to discover some errors.
After signing the signature pad and pressing the save signature button I get these errors in Firebug
Warning: fopen(xampp/htdocs/alpha/site6/images/sign_42281643871777767.png): failed to open stream: No such file or directory in C:\xampp\htdocs\alpha\site6\post.php on line 20
Warning: fwrite() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\alpha\site6\post.php on line 21
Warning: fclose() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\alpha\site6\post.php on line 22
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''signatures' ('session', 'image_location') VALUES ('127.0.0.1', 'sign_42281643871' at line 1
Since I don't have any knowledge of Jquery or Ajax and how they are creating the image and attempting to post it to a folder I'm pretty much stuck at this point!
seems I'm answering my own problems, I've figured out what the fopen errors were, I wasn't using an absolute path so adding a / before the start of the path cleared up everything except for the last error of this:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''signature' ('session', 'image_location') VALUES ('127.0.0.1', 'sign_11814198867' at line 1
Related
I hope I am asking this the correct way and thanks in advance for any advice! I have been trying to utilize this tutorial for a part on my own site:
https://developers.google.com/maps/documentation/javascript/mysql-to-maps
After trying many versions of my own code unsuccessfully, I decided to go ahead and step by step walk through the tutorial - even creating a new MYSQL DB exactly like in the tutorial...
In the tutorial example, they use an actual .xml file to read the data from:
// Change this depending on the name of your PHP or XML file
downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
However, just like the commented line says above the code "PHP File" - meaning you could use a PHP file there instead of an .xml file which would then dynamically generate the XML code based on the DB query.
They show 3 different ways to get the XML code from the DB and I have tried all 3 ways with the same exact results.
When I run the index.html page I get just the map showing up with no markers at all
If I run just the php file that generates the XML code, nothing shows up in the browser (just a blank white page) -- HOWEVER -- when I view the page source, it shows me the XML perfectly!
If I take that generated XML from my PHP file and copy/paste it into an .xml file and then call that .xml file in the downloadurl function, it all works perfectly!
So, therein lies my question.
What piece am I missing that would allow me to use the PHP file to dynamically generate the XML versus needing a separate XML file in my directory too.
The code I am using is the same exact code they have in the tutorial page.
Thanks in advance!!
EDIT - here are the 2 php pages. The convert-xml.php is for generating the info from MYSQL db. It's, getting the info from the db because when I view source it shows the xml tree like it should be. It;'s just not writing it to the browser or working in the downloadurl function to display the markers on the map.
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Using MySQL and PHP with Google Maps</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var customLabel = {
restaurant: {
label: 'R'
},
bar: {
label: 'B'
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(-33.863276, 151.207977),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('convert-xml.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY_IS_HERE&callback=initMap">
</script>
</body>
</html>
convert-xml.php
<?php require 'conn-info.php';?>
<?php
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false
$dom->formatOutput = true;
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// connect to db
$membermap_conn = mysql_connect($membermap_server, $membermap_user, $membermap_password, $membermap_database);
if ($membermap_conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $membermap_conn->connect_errno . ") " . $membermap_conn->connect_error; }
// select the db
$db_selected = mysql_select_db($membermap_database, $membermap_conn);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Pull the zip / user information out of the database.
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// Add to XML document node
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("id",$row['id']);
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("type", $row['type']); }
echo $dom->saveXML();
?>
This is the code in my js
(function(){
var video = document.getElementById('video'),
canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
photo = document.getElementById('photo'),
vendorUrl = window.URL || window.webkitURL;
datas = canvas.toDataURL('images/png');
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getMedia({
video: true,
audio: false
}, function(stream){
video.src = vendorUrl.createObjectURL(stream);
video.play();
}, function(error){
});
document.getElementById('capture').addEventListener('click',function(){
context.drawImage(video, 0, 0, 400, 300);
photo.setAttribute('src', canvas.toDataURL('images/png'));
datas = canvas.toDataURL('images/png');
});
var canvasData = canvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'webcam.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
})();
This is the php code to receive the data
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
echo "true";
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
<head>
<meta charset="UTF-8">
<Title>Document</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="booth">
<video id = "video" width="400" height="300"></video>
Snap Shot
<canvas id="canvas" width="400" height="300"></canvas>
<img id ="photo" name = "photo" src="images/events/default.png" alt="Photo of you">
</div>
<script src="js/photo.js"></script>
</body>
<?php
?>
The application intends to take a snapshot of the user and saves the photo via javascript. I am trying to find a way to send the data back to php and utilize it to save into the database. I understand it is saved in base64 encode. I tried different methods of Ajax including the one I have saved, but the data tends to not send any data to the php folder.
Thank you in advanced.
I just suggest you to check some of you code points:
Form content type. To upload files you must use "multipart/form-data"
ajax.setRequestHeader('Content-Type', 'multipart/form-data');
You can use FormData class in JS to make form data before sending:
https://developer.mozilla.org/en/docs/Web/API/FormData/append
Canvas function "toDataURL" have no mime types "images/png". Just "image/png"
I am using Codeigniter and want to show progress of XML import.
but issue i am facing is
When view load, it stuck on loading (blank page) and when i can see view its shows 100% done.
my code as bellow
$i=0;
$count=sizeof($record->List);
foreach($record->List as $Item)
{
$i++;
echo "processing ".$i." of ".$count;
---processing code which takes times to process---
---processing code which takes times to process---
}
this code is in view but when i click on link to load this view, i have to wait for all process to complete and then i can see view when all process is done.
what i want is:
Show view (empty).
Then keep on printing each line as loop go.
Thanks
Here you got a example for progress bar using AJAX:
index.php
<?php
// Start the session.
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Progress Bar</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<style>
#progress {
width: 500px;
border: 1px solid #aaa;
height: 20px;
}
#progress .bar {
background-color: #ccc;
height: 20px;
}
</style>
</head>
<body>
<div id="progress"></div>
<div id="message"></div>
<script>
var timer;
// The function to refresh the progress bar.
function refreshProgress() {
// We use Ajax again to check the progress by calling the checker script.
// Also pass the session id to read the file because the file which storing the progress is placed in a file per session.
// If the call was success, display the progress bar.
$.ajax({
url: "checker.php?file=<?php echo session_id() ?>",
success:function(data){
$("#progress").html('<div class="bar" style="width:' + data.percent + '%"></div>');
$("#message").html(data.message);
// If the process is completed, we should stop the checking process.
if (data.percent == 100) {
window.clearInterval(timer);
timer = window.setInterval(completed, 1000);
}
}
});
}
function completed() {
$("#message").html("Completed");
window.clearInterval(timer);
}
// When the document is ready
$(document).ready(function(){
// Trigger the process in web server.
$.ajax({url: "process.php"});
// Refresh the progress bar every 1 second.
timer = window.setInterval(refreshProgress, 1000);
});
</script>
</body>
</html>
checker.php
<?php
// The file has JSON type.
header('Content-Type: application/json');
// Prepare the file name from the query string.
// Don't use session_start here. Otherwise this file will be only executed after the process.php execution is done.
$file = str_replace(".", "", $_GET['file']);
$file = "tmp/" . $file . ".txt";
// Make sure the file is exist.
if (file_exists($file)) {
// Get the content and echo it.
$text = file_get_contents($file);
echo $text;
// Convert to JSON to read the status.
$obj = json_decode($text);
// If the process is finished, delete the file.
if ($obj->percent == 100) {
unlink($file);
}
} else {
echo json_encode(array("percent" => null, "message" => null));
}
process.php
<?php
// Start the session.
session_start();
// The example total processes.
$total = 20;
// The array for storing the progress.
$arr_content = array();
// Loop through process
for ($i = 1; $i <= $total; $i++) {
// Calculate the percentation
$percent = intval($i / $total * 100);
// Put the progress percentage and message to array.
$arr_content['percent'] = $percent;
$arr_content['message'] = $i . " row(s) processed.";
// Write the progress into file and serialize the PHP array into JSON format.
// The file name is the session id.
file_put_contents("tmp/" . session_id() . ".txt", json_encode($arr_content));
// Sleep one second so we can see the delay
sleep(1);
}
Just that you write it on the CI and create a tmp folder, and you point a path to it in script. Good luck!
If I embed my XHR file into my HTML document directly, everything works fine. As soon as I src it via
<script type="text/javascript" src="js/ajax_gallery.js">ajax_json_gallery('gallery');</script>
Nothing works, and I get no errors. I'm assuming it's something to do with the XHR being created in a separate file to the HTML. I just don't like XHR script cluttering up my HTML, I just want to load as an external JS file.
I've moved my main 3 scripts, galleryHandle.php, XHR.js, ajax_gallery.html all to the same dir level to keep things simple. And the gallery images are in a folder called "gallery", also on the same level.
Here's my code:
HTML
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/gallery.css" />
</head>
<body>
<div id="pagetop"></div>
<div id="thumbnailbox"></div>
<div id="pictureframe"></div>
<script type="text/javascript" src="XHR.js">ajax_json_gallery('gallery');</script>
</body>
</html>
JavaScript
function ajax_json_gallery(folder) {
"use strict";
var httpRequest = new XMLHttpRequest();
document.getElementById("pagetop").innerHTML = "dynamic ajax json gallery";
var thumbnailbox = document.getElementById("thumbnailbox");
httpRequest.open("POST", "galleryHandle.php", true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
var pictureframe;
pictureframe.innerHTML = "<img src='"+data.img1.src+"'>";
thumbnailbox.innerHTML = "";
for (var obj in data) {
if (data[obj].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+data[obj].src+'\')"><img src="'+data[obj].src+'"></div>';
}
}
}
};
httpRequest.send("folder="+folder);
thumbnailbox.innerHTML = "Loading...";
}
function putinframe(src) {
"use strict";
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src = " '+src+' " >';
}
PHP
<?php
header("Content-Type: application/json");
//bring in folder name
$folder = $_POST["folder"];
//start componding json
$jsonData = '{';
//compound directory path
$dir = $folder."/";
//open directory
$dirHandle = opendir($dir);
//init while looop
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && strpos($file, '.jpg')){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
I understand there are some redundancies in my code but it's just a tutorial I'm going through to learn the basics of JSON building with POST, XHR.
Anyway, help appreciated as always.
Thanks
Explanation
FROM W3C:
<script type="text/javascript" src="myscript.js">
alert('I am pointless as I won\'t be executed');
</script>
Upon meeting this element in a page, browsers will then load the file myscript.js and execute it. Any content inside the script element itself will be skipped when you provide a src attribute. The [last] example will load the file myscript.js and execute the code in it but will not execute the alert inside the script element at all.
Solution
Try the following in your head tags:
HTML
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">
ajax_json_gallery('gallery');
</script>
<script type="text/javascript" src="XHR.js">
You can't have src attribute and javascript both in a single tag. Separate them out. Like this...
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">ajax_json_gallery('gallery');</script>
I'm trying to display an image exported from a flash BitmapData in a basic webpage.
The export from flash works perfectly :
import flash.display.BitmapData;
var vBitmap = new BitmapData(300, 400, true, 0x000000);
vBitmap.draw(themovieclip_mc);
btn1.onRelease = function() {
var vLV = new LoadVars();
vLV.tableData = new Array();
for (i=0; i<300; i++) {
for (j=0; j<400; j++) {
vLV.tableData.push(vBitmap.getPixel(j, i));
}
}
vLV.send("webpage.php", "_self", "POST");
};
Then I get the image in the webpage.php file
<?php
$lv = $_POST['tableData'];
$temp = explode(",",$lv);
settype($temp[1],'integer');
$img = imagecreatetruecolor(300,400);
$k = 0;
for($i=0; $i<300; $i++){
for($j=0; $j<400; $j++){
imagesetpixel($img,$j,$i,$temp[$k]);
$k++;
}
}
$temporary_file_name = tempnam("/tmp");
imagejpeg($img,"$temporary_file_name",100);
?>
<html>
<img src="/tmp/<?php echo $temporary_file_name; ?>" />
<h1>Lorem ipsum</h1>
<p>lorem ipsum dolor sit amet</p>
</html>
the above code does NOT work, I can't find a way to display the image embedded in the webpage. Any help woud be really appreciated.
I am assuming that the insertion of the image data into the web page is your only problem. (without data, it's impossible to tell how well the image generation process itself works.)
I can't find a way to display the image embedded in the webpage
There isn't any good way to do this. You need to get the image from a separate image resource, there's no way around it (except data: URIs but those are broken).
You could write the avatar file into a temporary file:
$temporary_file_name = tempnam("/path/to/somedir");
imagejpeg($img,"$temporary_file_name",100);
then in the HTML, output:
<img src='/somedir/<?php echo $temporary_file_name; ?>' />
you would have to add some mechanism to remove the temporary file later.
So, I finally found my way through this.
That might not be the best way to do it, but at least it works.
//AS3
import com.adobe.images.JPGEncoder;
function createJpg(aMovieClip, aQuality){
var vSource = new BitmapData(200, 304, true, 0 );
vSource.draw(aMovieClip, new Matrix(1,0,0,1,100,152)); // decale de width/2 et height/2
var vEncoder = new JPGEncoder(aQuality);
var vByteArray = vEncoder.encode(vSource);
return vByteArray;
};
// export image to server
function exportJpg(aMovieClip){
var vByteArray = createJpg(aMovieClip, 80);
var vRequest:URLRequest = new URLRequest('URL_TO_THE_PHP_FILE');
var vLoader: URLLoader = new URLLoader();
vRequest.contentType = 'application/octet-stream';
vRequest.method = URLRequestMethod.POST;
vRequest.data = vByteArray;
navigateToURL(vRequest, "_self");
};
// save image on users computer
function saveJpg(aMovieClip, aString){
var vByteArray = createJpg(aMovieClip, 80);
var vFR = new FileReference();
vFR.save(vByteArray, aString);
};
Then the PHP/HTML file
<?php
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
$img = $GLOBALS["HTTP_RAW_POST_DATA"];
$prefix = "foo";
$path = "/full/server/path/to/directory/with/777/permissions";
// give a unique name to the file
$name = $prefix.md5(time().rand());
$temporary_file_name = $path.'/'.$name.'.jpg';
$fp = fopen($temporary_file_name, 'wb');
fwrite($fp, $img);
fclose($fp);
// find the name of the image without the full server path
$array = explode("/", $temporary_file_name);
$length = count($array);
$filename = $array[$length - 1];
//give a path to the image file
$imagepath = "http://www.domain.com/directory/".$filename;
}else{
// error : the POST data was not found
}
?>
<html>
<head>
</head>
<body>
<h1>Lorem ipsum</h1>
<p><img src="<?php echo $imagepath; ?>"</p>
</body>
</html>