I'm trying to upload file using flash So
I've following code in action-script:
var fileRef:FileReferenceList = new FileReferenceList();
fileRef = new FileReferenceList();
fileRef.browse(new Array( new FileFilter( "Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png" )));
fileRef.addEventListener(Event.SELECT, fileSelectHandler);
var uploadURL:URLRequest = new URLRequest();
var uploadPhotoScript:String = "http://localhost/uploader/upload.php";
uploadURL.url = uploadPhotoScript;
function fileSelectHandler(event:Event):void {
for each(var fileToUpload:FileReference in fileRef.fileList){
uploadSingleFile(fileToUpload);
}
}
function uploadSingleFile(file:FileReference):void {
file.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
file.upload(uploadURL);
file.addEventListener(Event.COMPLETE, completeHandler);
}
function onUploadProgress(e:ProgressEvent):void
{
var f:FileReference = e.currentTarget as FileReference;
var fileName:String = f.name; //Now I know which file it is, I can update accordingly
var progress:Number = (e.bytesLoaded / e.bytesTotal) * 100; //shows percent, you might want to round this off using Math.round(number);
}
function completeHandler(event:Event):void {
trace("upload complete");
}
upload.php:
<?php
if(isset($_SERVER["HTTP_REFERER"]){
$ref=$_SERVER["HTTP_REFERER"];
$ref=explode($ref,"/");
$ref=$ref[2];
if($ref=="localhost"){
if(!empty($_FILES)){
$tmpfile = $_FILES['Filedata']['tmp_name'];
$targetfile = dirname(__FILE__) . '/' . $_FILES['Filedata']['name'];
move_uploaded_file($tmpfile, $targetfile);
}
}
else{
header("location:NotLocalhost.html");
exit;
}
}
else{
header("Location:NOREF.html");
exit;
}
?>
This code works fine in all browsers except firefox. coz In firefox $_SERVER["HTTP_REFRER"] becomes null and NOREF.html is displayed.
Also in firefox when the script is accessed by another html or php script then works fine, but when is accessed vai swf movie which is in turn <embeded> in html page. Then the REFERER becomes null.
Any ideas? How can I solve this?
Related
I'm going to upload files from flash to server. When user begin, input his username, then I send it to php, this way:
var myusername:String = username.text;
username.restrict = "A-Za-z0-9";
login_btn.addEventListener(MouseEvent.CLICK,login);
function login (evt:MouseEvent):void{
var loader : URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://domain/uploads/upload.php");
request.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
var userid:String = myusername;
variables.ID = userid;
request.data = variables;
loader.load(request);
}
upload.php :
<?php
$myuser = $_POST['ID'];
$uploads_dir = './uploads/'.$myuser;
if( $_FILES['Filedata']['error'] == 0 ){
if( move_uploaded_file( $_FILES['Filedata']['tmp_name'],
$uploads_dir.$_FILES['Filedata']['name'] ) ){
exit();
}
}
echo 'error';
exit();
?>
The problem is that files upload to uploads folder not in user folder. Anyone could help me please?
What is the value of $_POST['ID']?
I don't see you setting that anywhere in the request. There's this:
variables.UID = userid;
But wouldn't that be $_POST['UID'] and not $_POST['ID']?
I'm trying to upload a canvas.todataurl() image (getUserMedia) to server using jQuery post and php to handle the data, but I'm having some problems. All the images I'm uploading end up being corrupted, half of the image is missing. I also have a MySQL database where I'm storing data related to the image (title, text, date and the like). It seems that the more I have the related data the more the image get corrupted.
Therefore, I'm wondering is this a browser limitation or does this have something to do with jQuery post. I've also checked the PHP max_post_size and it's 16mb, so that shouldn't be a problem. I don't have access to the server settings. I'm quite puzzled with this, what can I do? Is it possible to divide the canvas.todataurl() to multiple parts and then post?
JavaScript
window.addEventListener('DOMContentLoaded', function() {
var video = document.getElementById('videoStream');
var canvas = document.getElementById('canvasImage');
var status = document.getElementById('status');
var button = document.getElementById('button');
//var others = document.getElementById('others');
var imageHolder;
document.getElementById('form').style.display = 'none';
var image = null; // kuvan datauri joka lähtee php:lle
window.URL || (window.URL = window.webkitURL || window.mozURL || window.msURL);
navigator.getUserMedia || (navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia);
// toString : function() {return "video,audio";} canarya varten
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true, audio: false, toString : function() {return "video,audio";}}, onSuccess, onError);
} else {
status.innerText = "getUserMedia is not supported in your browser, sorry :(";
}
function onSuccess(stream) {
var source;
if (window.webkitURL) {
source = window.webkitURL.createObjectURL(stream);
} else {
source = stream; // Opera ja Firefox
}
video.width = 500;
video.height = 375;
video.autoplay = true;
video.src = source;
}
function onError() {
status.innerText = "Please allow access to your webcam.";
}
button.addEventListener('mousedown', function() {
// Poistetaan aikaisempi kuva jos sellaista on
//document.body.removeChild(imageHolder);
// luodaan kuva uudestaan
imageHolder = document.createElement('figure');
imageHolder.id = 'imageHolder';
document.body.appendChild(imageHolder);
img = document.createElement('img');
imageHolder.appendChild(img);
// kuva on yhtäsuuri kuin video
canvas.width = video.width;
canvas.height = video.height;
img.width = 350;
img.height = 225;
// piirretään canvasille kuva videosta
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
}, false);
button.addEventListener('mouseup', function() {
// Canvasilta kuvaksi levylle tallentamista varten
canvas.style.display = 'none';
video.style.display = 'none';
button.style.display = 'none';
others.style.display = 'none';
document.getElementById('form').style.display = 'block';
image = canvas.toDataURL('image/png');
img.src = image;
}, false);
// jquery post
$('#send').click(function(){
var image2 = image.replace('data:image/png;base64,', '');
$.post('upload.php',
{
title: $('#title').val(),
blog: $('#blog').val(),
category: $('#category').val(),
author: $('#author').val(),
imagename: image2
});
});
}, false);
PHP upload.php
define('UPLOAD_DIR', 'images/');
$img = $_POST['imagename'];
$img = str_replace(' ','+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Tiedoston tallennus ei sitten onnistu millään...';
$imagename = $file; // this is the file name for the MySQL database
My problem is (I think) image = canvas.toDataURL('image/png'); and the jQuery post.
The canvas.toDataUrl() string is about 700 000 letters long.
You might wanna try this:
<?php
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++)
$decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
?>
I got it from here: http://www.php.net/manual/en/function.base64-decode.php#92980
The code basically tries to partially decodes the base64 string. I haven't tested this though. I've never dealt with base64 images as big as what you're working with.
Split it, use two, variables and merge in php, works fine. ;-)
var resourcelength_all = resource.length;
var resourcelength_split = resourcelength_all / 2;
var resource_part1 = resource.substr(0, resourcelength_split);
var resource_part2 = resource.substr(resourcelength_split, resourcelength_all);
Okay so I have a PHP script which handles file uploads, KML files specifically, extracts the center point and the location of the uploaded file, saves these details in text files, and then loads another page via "header". This other page then uses AJAX calls to set variable names as gathered from the text files, for the location of the KML file and the center point, in order to call the Google Maps API to show the KML layer upon a map.
That is what is supposed to happen, but instead nothing appears. I browse for my KML file, hit the upload button, and a blank page is shown. When I check my server, the file as been uploaded and the relevant details written into their respective text files, so obviously something is going wrong when I try to call the Google Maps API.
PHP upload and file info saving:
<?php
//Check that we have a file
if((!empty($_FILES["UploadedFile"])) && ($_FILES['UploadedFile']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 3Mb
$filename = basename($_FILES['UploadedFile']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "kml") && ($_FILES["UploadedFile"]["size"] < 3145728)) {
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/kml/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['UploadedFile']['tmp_name'],$newname))) {
findCenter($newname);
saveName($newname);
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["UploadedFile"]["name"]." already exists";
}
} else {
echo "Error: Only .kml files under 3Mb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
function findCenter($file) {
$kmlContent = file_get_contents($file);
$startName = "#sh_green-circle";
$endName = "#sh_red-circle";
$startCoords = getCoords($kmlContent, $startName);
$endCoords = getCoords($kmlContent, $endName);
$startLat = substr($startCoords, strrpos($startCoords, ',') +1);
$startLong = substr($startCoords, 0, strrpos($startCoords, ','));
$endLat = substr($endCoords, strrpos($endCoords, ',') +1);
$endLong = substr($endCoords, 0, strrpos($endCoords, ','));
$midLat = ($startLat+$endLat)/2;
$midLong = ($startLong+$endLong)/2;
$midCoord = "$midLat,$midLong";
$saveCenter = "kmlcenter.txt";
$fh = fopen($saveCenter, 'w') or die ("Can't create file");
$stringData = $midCoord;
fwrite($fh, $stringData);
fclose($fh);
}
function getCoords($kml, $name) {
$startSearch = strpos($kml, $name);
$midSearch = strpos($kml, "<coordinates>", $startSearch+1);
$endSearch = strpos($kml, "</coordinates>", $midSearch+1);
$longlat = substr($kml, $midSearch+13, $endSearch-($midSearch+13));
return $longlat;
}
function saveName($filename) {
$saveFile = "kmlfilename.txt";
$fh = fopen($saveFile, 'w') or die("Can't create file");
$stringData = "$filename";
fwrite($fh, $stringData);
fclose($fh);
header("Location: initgmaps.html");
}
?>
Map intitialisation:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB8P7CzxiwQFf-RdK9QVRpH9se8AsMSsjEsensor=false"></script>
<script type="text/javascript">
function initialize() {
var kmlName = getName()
var kmlCoords = getCoords()
var mapcenter = new google.maps.LatLng(kmlCoords);
var myOptions = {
zoom: 11,
center: mapcenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("infoArea"), myOptions);
var kmlLayer = new google.maps.KmlLayer(kmlName);
kmlLayer.setMap(map);
}
</script>
Relevant AJAX functions:
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function getName(){
var ajaxRequest; // The variable that makes Ajax possible!
var kmlName;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
kmlName = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "kmlfilename.txt", false);
ajaxRequest.send(null);
}
//-->
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function getCoords(){
var ajaxRequest; // The variable that makes Ajax possible!
var kmlCoords;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
kmlCoords = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "kmlcenter.txt", false);
ajaxRequest.send(null);
}
//-->
And of course in the body of initgmaps.html I have:
onload="initialize()"
infoArea is the ID for my inline frame.
Can anyone see why it doesn't load? I'm completely and utterly new to web development, learning as I go, so sorry if the code is terrible and I'm sure I've made some obvious errors. Many thanks.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB8P7CzxiwQFf-RdK9QVRpH9se8AsMSsjEsensor=false"></script>
You have missed an ampersand here... Should be:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=[[YOUR-GMAPS-KEY]]&sensor=false"></script>
(Where [[YOUR-GMAPS-KEY]] is your Google Maps Key - "AIzaSyB8P7CzxiwQFf-RdK9QV...".)
Try adding an ampersand '&' after your key and before the sensor=false parameter.
Additionally
var kmlCoords = getCoords()
is javascript, but function getCoords() is PHP. Javascript cannot execute a PHP function.
the error might be caused by not following this format:
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"
see, after "YOUR_API_KEY" there shouldn't be "sensor=false".
try it. hope it works.
I use the script below to create images on the fly, and display them via ajax and a div however the PHP image header is not being read and instead of an image been displayed I just get the image source code. Any ideas how force php to read the header as an image?
<?php
header('Content-Type: image/jpeg'); // JPG picture
$root = $_SERVER['DOCUMENT_ROOT'];
require("$root/include/mysqldb.php"); //mysql login details
require("$root/include/mysql_connect.php"); //mysql connect
if(!empty($small)) { $size = "50"; $folder = "thumnail_user_images"; } else { $size = "250"; $folder = "large_user_images"; }
$dice_image = $_GET["image"];
if (!file_exists("$root/$folder/$dice_image"))
{
require("$root/include/image_resizing_function.php"); //create image
$image = new SimpleImage();
$image->load("$root/raw_user_images/$dice_image");
$image->resizeToWidth($size);
$image->save("$root/$folder/$dice_image");
$image->output();
}
else {
readfile("$root/$folder/$dice_image");
}
And this is the Ajax a use to swap out the images:
<script type="text/javascript">
var bustcachevar=1
var loadedobjects=""
var rootdomain="https://"+window.location.hostname
var bustcacheparameter=""
function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest)
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar)
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}
function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){
if (file.indexOf(".js")!=-1){
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" "
}
}
}
</script>
Make sure there's no extra whitespace after the closing ?> in the php files referenced by require statements. I had that problem and was scratching my head for days before finding the answer.
Hi I'm working on actionscript, saving a raw image from camera then POST with save.php then
I want save.php echo back the variable which is a file name that have just generated by save.php to actionscript
see this line:
var urlParameter:String = "images/test_01.php?img=" + "myfileURL";
navigateToURL(new URLRequest(urlParameter), "_blank");
Thanks in advance
this is AS3 code
function onSaveJPG(e:Event):void{
var myEncoder:JPGEncoder = new JPGEncoder(100);
var byteArray:ByteArray = myEncoder.encode(bitmapData);
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var saveJPG:URLRequest = new URLRequest("save.php");
saveJPG.requestHeaders.push(header);
saveJPG.method = URLRequestMethod.POST;
saveJPG.data = byteArray;
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, sendComplete);
urlLoader.load(saveJPG);
function sendComplete(event:Event):void{
warn.visible = true;
addChild(warn);
warn.addEventListener(MouseEvent.MOUSE_DOWN, warnDown);
warn.buttonMode = true;
}
function warnDown(e:MouseEvent):void{
var urlParameter:String = "images/test_01.php?img=" + "myfileURL";
navigateToURL(new URLRequest(urlParameter), "_blank");
// navigateToURL(new URLRequest("images/"), "_blank");
// +saveJPG:URLRequest
// navigateToURL(new URLRequest("images/test_01.php?img=+saveJPG:URLRequest"), "_blank");
warn.visible = false;
}
} // move onSave JPG
} close to here instead of after sendComplete
warn.visible = false;
this is save.php
<?php
if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
$img = $GET["img"];
$filename = "images/poza". mktime(). ".jpg";
file_put_contents($filename, $jpg);
echo "thisPic=" . $filename;
// echo $filename;
} else{
echo "Encoded JPEG information not received.";
}
?>
In your case you are just using mktime() for the file name, and images/poza is hard coded. You can post the file name along the jpeg data from flash, and when onSaveJPG is called you simply display the file name to the user.
Below is example of how you can send file_name.
var JPGFileName = YOUR TIME FUNCTION
var saveJPG:URLRequest = new URLRequest("save.php?file_name=" + JPGFileName);
saveJPG.requestHeaders.push(header);
saveJPG.method = URLRequestMethod.POST; saveJPG.data = byteArray;