I have embedded aviary into my webpage and it is working fine but I am unable to use the file_get_contents command to grab the saved image.
the aviary code:
JS:
<!-- Load Feather code -->
<script type="text/javascript" src="http://feather.aviary.com/js/feather.js"></script>
<!-- Instantiate Feather -->
<script type='text/javascript'>
var featherEditor = new Aviary.Feather({
apiKey: '*********',
apiVersion: 3,
theme: 'light', // Check out our new 'light' and 'dark' themes!
tools: 'crop,orientation,brightness,sharpness,redeye,effects,stickers,focus,contrast,whiten,warmth,colorsplash,enhance,saturation,blemish,draw,text,frames',
appendTo: '',
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
onError: function(errorObj) {
alert(errorObj.message);
},
postUrl: 'http://example.com/featherposturl'
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
HTML:
<div id='injection_site'></div>
<img id='image1' src='photo.jpg' style="max-height:360px;" on/>
<p><input type='image' src='http://images.aviary.com/images/edit-photo.png' value='Edit photo' onclick="return launchEditor('image1', document.getElementById('image1').src);"/></p>
According to the aviary documentation I can grab the temp file that has been created on the aviary server but using this php code:
<?php
$image_data = file_get_contents($_REQUEST['url']);
file_put_contents("photo.jpg",$image_data);
?>
When I run this it errors out with this error
[24-Sep-2013 12:14:16 UTC] PHP Warning: file_get_contents() [function.file-get-contents]: Filename cannot be empty in......
Does anyone have any experience as to how I can grab the file that has been created on the aviary server and upload a copy to my server.
UPDATE
I notice a file called 'photo.jpg' is added to the server with a filesize of 0kb. I am assuming that this is from the file_put_contents("photo.jpg",$image_data); but the image data is blank as this is the error if the file_get_contents
Any ideas?
Please check that on your sever allow_url_fopen = 0
if it's value is 1 file_get_contents can't work
it that case you can use curl
Aviary posts back to a URL of your choice with a link to the file saved on their servers. So, you need to add a route on your server with the server-side code snippet above and make sure the postUrl you specify is the URL on your server that will call this code.
I had the same problem, this answer is probably a little late now, but I got around it this way. Its not the best way but it does work
In your javascript change this:
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
to This:
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
var old_image = $('#oldimage').val(); //this is a hidden field with the HTML LINK for the original image on your server
$.ajax({
url : 'PHP Processing page',
type : 'POST',
dataType : 'JSON',
data : {oldimage : old_image, newimage : img.src},
success : function (json) {
console.log(json);
}
});
}
HTML:
<input id="oldimage" type="hidden" value="ORIGINAL IMAGE" />
<button class="button special fit" onclick="return launchEditor('image1', 'ORIGINAL IMAGE');">Edit This Image</button>
In the PHP processing page:
$default = getenv("DOCUMENT_ROOT");
define("SITEROOT",$default."/yoursite/");
define("SITEHTMLROOT", "http//www.yoursite.com/");
$oldimage = str_replace(SITEHTMLROOT, SITEROOT, $_POST['oldimage']);
$newimage = $_POST['newimage'];
copy($newimage, $oldimage);
As long as allow_url_fopen is set to on/1 this will work
You don't need to add the
postUrl: 'http://example.com/featherposturl'
line to do it this way
As this post is very old, if you did find a good way of doing this would you share it?
Related
My current code is:
Play.save = function() {
//Hide the buttons
this.printButton.visible = false;
this.saveButton.visible = false;
this.backButton.visible = false;
//Force the game to re-render.
this.game.cameras.render(); //generally not recommended if you can help it
//Get the canvas information
var img = this.game.stage.canvas.toDataURL("image/octet-stream");
this.saveajax(img);
//Show UI again.
this.printButton.visible = false;
this.saveButton.visible = true;
this.backButton.visible = true;
}
Play.saveajax = function(img){
$.ajax
({
url: "http://localhost/ourthing/character/save.php",
type: "POST",
cache: false,
data: {
img: img
}
});
}
The file 'save.php' works (when i simply open the file). It will execute a query which it has to do. Problem here is: with this script i want to update a user with the given post data (img). But it doesnt execute on this request.
(i create data for var img and send this data to the saveajax function, which will open save.php to execute the query).
Im very new to JS/ajax. Does anyone can help me?
Best regards
apparently I cant comment, so my question is what are you getting on save.php
with command like
error_log(print_r($_REQUEST,true));
I suspect JSON issue here. can we see save.php?
Ok didn't see your previous comment, scrap that - your Jquery is not included.
Answer:
I had to include jQuery:
<script src="assets/js/jquery.js" ></script >
Thanks #Don'tVoteMeDown and #Lixus
Save.php file:
$db = framework::getDBO();
$data = array(
'canvas_character' => $_POST['img'],
);
$db->where('id', 1);
$db->update('ot_users', $data);
(i use my own framework)
I am using simpleImage, a php image manipulation library.. I am trying to rotate the image externally using ajax and replaceWith. It replaces the image and everything but it wont refresh when rotated..
index.php -
//Submit Form
function subForm() {
event.preventDefault();
var name = $('#target').val();
console.log(name);
$.post("rotate.php", {name: name},
function(data) {
$("#preview").replaceWith( '<img id="replace" src="'+data+'"/>' );
});
}
<img src="'.$target.'" id="preview"/>
<form method="post" action='' id="rotateForm" data-ajax="false">
<input type="submit" id="rotate" onclick="subForm();" value="rotate">
</form>
** UPDATED**
rotate.php -
$time = time();
$newImg = $_POST['name'];
$img = new abeautifulsite\SimpleImage($newImg);
$img->rotate(90)->best_fit(500, 500)->save();
echo $newImg.'?'.$time;
The image rotates but doesn't update on the page with out the page being reloaded.. Am I using the wrong approach here?
Images do usually get cached by the browser.
The problem:
you show some image with a specific src like someimage.jpg
You rotate that image and provide it with the same src someimage.jpg
the browser will load the old one from the cache!
To prevent that you could simply request a brand new one using a timestamp like
someimage.jpg?t=1476400456961
and the browser will load a clean someimage.jpg from the server.
A JS solution is:
function subForm() {
event.preventDefault();
var name = $('#target').val();
console.log(name);
$.post("rotate.php", {name: name}, function(data) {
var tStamp = +new Date(); // Generate always a new timestamp milliseconds value
$("#preview").replaceWith( '<img id="replace" src="'+ data+"?t="+ tStamp +'"/>' );
});
}
You have rewrite the src attribute of your tag so that the image loads again.
This PHP code works when I use HTML <input type="file">, but not when I use the jQuery file upload script at the very bottom.
I believe all .js & .css files are accounted for and working (tested)
I believe the uploadUrl: 'doc_upload.php', fileInputName: 'userfile' are correct. Don't know 'cause no errors are showing.
Using echo getcwd();, I believe I'm using correct paths
I'm only uploading a 1 kb .TXT file
I get no errors and all error reporting is on and maxed
One thing that is also not working, which I'm saying to possibly give a clue, is the upload & cancel buttons next to the file name are not showing all though clicking on them does seem to work.
Echo'ing $_POST shows me nothing on submit, but I think that's a javascript thing; not sure as I'm a beginner (3-months).
PHP page
$filename = $_FILES['userfile']['name'];
$tmpname = $_FILES['userfile']['tmpname'];
$filesize = $_FILES['userfile']['size'];
$filetype = $_FILES['userfile']['type'];
$fp = fopen($tmpname, 'r');
$content = fread($fp, filesize($tmpname));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc()) {
$filename = addslashes($filename);
}
$filename = preg_replace('/[ ]/', '~', $filename);
$document_folder = $_SESSION['users_id'];
$destfile = "../_documents/".$document_folder."/".$_FILES['userfile']['name'];
move_uploaded_file( $_FILES['userfile']['tmpname'], $destfile );
HTML page
<link type="text/css" rel="Stylesheet" href="../jqx.base.css" />
<script type="text/javascript" src="../scripts/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../scripts/jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../scripts/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../scripts/jqwidgets/jqxfileupload.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#jqxFileUpload').jqxFileUpload({ width: 300, uploadUrl: 'doc_upload_jquery.php', fileInputName: 'userfile', autoUpload: true });
});
$('#jqxFileUpload').on('uploadStart', function (event) {
var fileName = event.args.file;
$('#log').prepend('Started uploading: <strong>' + fileName + '</strong><br />');
});
$('#jqxFileUpload').on('remove', function (event) {
var fileName = event.args.file;
$('#log').prepend('Removed file: <strong>' + fileName + '</strong><br />');
});
$('#jqxFileUpload').on('uploadEnd', function (event) {
var args = event.args;
var fileName = args.file;
var serverResponce = args.response;
});
</script>
</head>
<body>
<div id="jqxFileUpload">
</div>
<div id="log" style="margin-top: 20px;"></div>
<br />
</body>
</html>
mdpalow -
You probably aren't getting any errors or output because of the if statement at the top:
if (isset($_POST['submit']) && $_FILES['userfile']) {
Try putting this at the top to output all of your post variables so that you can determine what post variables are actually being sent (if any):
print_r($_POST);
I have done file uploads before but not with this specific library - my guess is that its just sending mulipart data instead of POST variables. Looking at the preview headers in the browser developer tools will also shed light as to what data is being sent.
The problem is that jQuery plugin uploads file via AJAX. In order to fix the issue please follow next steps:
Keep your HTML and PHP code in separate files.
In new PHP file remove isset($_POST['submit']) validation as there is no submission.
Simple question. I have a .doc file generated in my mojolicious app. I want to download it. That's my question, how do I get the browser to download it?
I'm using the CPAN module MsOffice::Word::HTML::Writer to generate the doc.
Here is the sub routine in my mojolicious app, it is called by an Ajax request in Jquery:
sub down_doc {
my $self = shift;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "My new Doc",
WordDocument => {View => 'Print'},
);
$doc->write("Content and Stuff");
my $save = $doc->save_as("/docs/file.doc");
$self->res->headers->content_disposition("attachment;filename=file.doc");
$self->res->headers->content_type('application/msword');
$self->render(data => $doc->content);
}
Here is my Ajax request in Jquery:
var request = $.ajax({
url: "/down_doc",
type: "post",
data: {'data': data},
});
request.done(function(response, textStatus, jqXHR) {
window.location.href = response;
});
I know that my Ajax "done" handler is wrong, I was just experimenting. How do I make my webpage prompt to save and download the .doc file?
You where pretty close, but I would recommend either of the following options...
File Download Processing with Mojolicious
You can install the plugin Mojolicious::Plugin::RenderFile to make this easy.
Example
plugin 'RenderFile';
sub down_doc {
my $self = shift;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "My new Doc",
WordDocument => {View => 'Print'},
);
$doc->write("Content and Stuff");
my $save = $doc->save_as("/docs/file.doc");
$self->render_file('filepath' => "/docs/file.doc");
}
Or if you want to only use Mojo the following will work, and is explained further at the link below.
use Cwd;
app->static->paths->[0] = getcwd;
sub down_doc {
my $self = shift;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "My new Doc",
WordDocument => {View => 'Print'},
);
$doc->write("Content and Stuff");
my $save = $doc->save_as("/docs/file.doc");
shift->render_static("/docs/file.doc");
}
Reference
This really isn't a problem on the server side, but rather that you can't save the response from an ajax request without using the (relatively new) File API. I would suggest replacing the ajax with a temporary form:
$('<form method="post" action="/down_doc">')
.append(
$('<input type="hidden" name="data">')
.attr("value", JSON.stringify(data))
)
.appendTo('body')
.submit();
When form is submitted and your /down_doc handler replies with the appropriate content-disposition header and the document data, the browser will do the work of handling the file save.
If you're not planning to use the file on the server after the request, this line can be removed:
my $save = $doc->save_as("/docs/file.doc");
I have some trouble sending the following html input type to my php script through ajax. I'm guessing that I have to define the file in tje js code hoverver how to do so when I have more variables that are taking information from the same file (se php code)?
<input id="imagefile" class="file" type="file" name="image" />
through this code
$("#addmedia").click(function(ev) {
ev.preventDefault();
var p = $("#p").val();
var mediatype = $("#mediatype option:selected").val();
var addmediatype = $("#mediatype option:selected").val();
var title = $("#title").val();
var video = $("#medialink").val();
var imagefile = $("#imagefile").val();
$.post("lib/action.php", {
mediatype: mediatype,
addmediatype: addmediatype,
title: title,
video: video,
addmedia: true
}, function(data) {
$("#notify").hide().html("<h1>!</h1><h2>" + data + "</h2>").slideDown(500);
setTimeout(function() { $("#notify").slideUp(500) }, 2500);
});
});
so that it works with my php upload script.
In my php code i use following variables to get infro from the file
if( $_POST['p'] == 1 ) {
$name = $_FILES['image']['name'];
$temp = $_FILES['image']['tmp_name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
(...)
}
When you use $().val for a file field, you're only getting the filename because of security restrictions.
One solution (for IE 10+, Chrome, FF) is to read the file contents using https://developer.mozilla.org/en-US/docs/Web/API/FileReader, base64 encode it and upload it. See Reading client side text file using Javascript
document.getElementById('file').addEventListener('change', readFile, false);
function readFile (evt) {
var files = evt.target.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function() {
console.log(this.result);
}
reader.readAsText(file)
}
Note that there are too many gotchas when uploading files through AJAX and can't possibly address with a concise answer as StackOverflow answers should be.
The easiest workaround is to not send it using AJAX, use a regular form upload, but target a hidden iframe so your page doesn't reload.
See:
Sending binary data in javascript over HTTP
Multiupload with PHP/JavaScript
http://www.html5rocks.com/en/tutorials/file/xhr2/
http://blueimp.github.io/jQuery-File-Upload/