I have created a QR code generating website. QR code is generated through PHP QR code generator library
by using this code
include_once "../phpqrcode/qrlib.php";
$PNG_TEMP_DIR = '../qrcodeImages/';
if (isset($_REQUEST['text'])) {
$content = $_REQUEST['text'];
$filename = $PNG_TEMP_DIR . 'qr' . md5($content) . '.png';
QRcode::png($content, $filename, 10);
echo $image = "<img class='img' src='qrcodeImages/" . basename($filename) . "'/>";
// $image_src = "qrcodeImage/" . basename($filename);
};
with this ajax call i append the QR code in the required div
$.ajax({
url: "code/single_input_to_qrcode.php",
type: "POST",
data: { text: jquery_plain_text },
success: (parms) => {
$("#downloadPart_img img").remove();
$("#downloadPart_img").append(parms);
}
});
and under QR code div I have placed a download button which is used to download the QR code
for downloading purpose I have used JavaScript library "File Saver"
code
var url = $("#downloadPart_img img").attr('src');
if (url == "img/white-qr-code.png") {
$("#error_msg_div").animate({ "top": "20px" });
error_msg = "Please generate a QR code before download";
error_msg_div.html(error_msg);
} else {
var file_name = url.substring(url.lastIndexOf('/') + 1);
url = "localhost/qrCodeGenerator/" + url;
saveAs(url, file_name);
}
But when user hit download button it show failed to download what kind of issue is that. I thinks this is because when the user hit the download button at the same time the file is saving in the folder so file is not available their at that time.
I have search a lot about that but I am fail to get its solution so now I am on this site to find solution so if some one now how to fix this problem so please help me.
Advance thanks
image of website and failed file at left bottom
Related
Am trying to upload image using ckeditor to my local file system in laravel for which i made a code which is working fine image is uploading properly everything is working fine except in ckeditor it doesn't show link here is my code :
<script>
window.onload = function() {
CKEDITOR.replace('long_description', {
filebrowserUploadUrl: '{{ route('upload',['_token' => csrf_token() ]) }}'
});
};</script>
on the rote part i make a route for upload like this :
Route::post('upload_image','CkeditorController#uploadImage')->name('upload');
and in the controller part i use this code :
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class CkeditorController extends Controller
{
public function uploadImage(Request $request) {
$CKEditor = $request->input('CKEditor');
$funcNum = $request->input('CKEditorFuncNum');
$message = $url = '';
if (Input::hasFile('upload')) {
$file = Input::file('upload');
if ($file->isValid()) {
$filename =rand(1000,9999).$file->getClientOriginalName();
$file->move(public_path().'/wysiwyg/', $filename);
$url = url('wysiwyg/' . $filename);
} else {
$message = 'An error occurred while uploading the file.';
}
} else {
$message = 'No file uploaded.';
}
return '<script>window.parent.CKEDITOR.tools.callFunction('.$funcNum.', "'.$url.'", "'.$message.'")</script>';
}
}
when i try to upload upload is working fine image goes in dir but in respose i got error :
[CKEDITOR] Error code: filetools-response-error. {responseText: "<script>window.parent.CKEDITOR.tools.callFunction(…linic/wysiwyg/4121dominospizza.jpg", "")</script>"}
so i search for error but i didn't get it the error description was
An error occurred when parsing the upload response. Text could not be parsed to JSON.
Additional data:
responseText: Upload response text.
help me out please thanks in advance.
I am trying to upload an image created from Java's toDataURL, submitted in a form automatically with javascript, captured by PHP and converted using imagecreatefrompng() and assigned to a variable.
Here is the code to start with:
Javascript code:
if(getImageData == true){
console.log("Saving avatar as image...");
window.setTimeout(function () {
imgData = renderer.domElement.toDataURL("image/png");
document.getElementById('avatarimg').src = imgData;
document.getElementById("timg").value = imgData;
console.log(imgData);
document.getElementById("form1").submit();
console.log("Avatar saved as PNG img.");
}, 300);
getImageData = false;
PHP code:
if($_POST['timg']){
$renderedav = imagecreatefrompng($_POST['timg']);
imageAlphaBlending($renderedav, true);
imageSaveAlpha($renderedav, true);
$target = "images/Avatars/";
$newname = md5($_POST['timg']);
echo ("<font color='#000000'>Image rendered. - " . $newname . " </font>");
$target = $target . $newname . ".png";
if(move_uploaded_file($renderedav, $target))
{ echo("File uploaded."); }else{echo("Error uploading file.");}
}
When I display the image as a raw img using the imgData, everything looks great, but I want to create an actual image from that data and upload it to a directory on my database using the name created in $newname. Is this possible to do? Am I going about it correctly? I know move_uploaded_file() is intended to move a suspended file from a file form element to a new location, but in my research I couldn't find another method that does this.
There are a couple things here that are not going to work:
You can not write text over top by echoing some html, you have to use a gdlib text function like imagettftext(). One note, you have to point to a font file to use it (Resource here). If you are not trying to write this echo ("<font color='#000000'>Image rendered. - " . $newname . " </font>"); over top of the image, disregard this part of the script HOWEVER, you still can not do it because if you echo anything (or have empty space before your script), it will corrupt the image.
You have to use imagepng() (Resource here) to save the file.
PHP Script:
if($_POST['timg']){
// Set file path info
$target = "images/Avatars/";
$newname = md5($_POST['timg']);
$target = $target.$newname.".png";
// Start gdlib functions
$renderedav = imagecreatefrompng($_POST['timg']);
imagealphablending($renderedav, true);
imagesavealpha($renderedav, true);
$fColor_white = imagecolorallocate($renderedav, 255, 255, 255);
// Path to truetype font
$font = 'font.TTF';
// Add text to image
imagettftext($renderedav, 25, 0, 75, 300, $fColor_white, $font, "Image rendered. - ".$newname);
// Here you output the png and use the second parameter to save to a destination
imagepng($renderedav,$target);
// Now you destroy the resouce
imagedestroy($renderedav);
}
im currently having an issue with the upload of files from the mobile version of the site im currently working with, I think the issue is related to the fact that the mobile version files are outside the public_hmtl folder inside a folder named m, this was done like this because the m.site.com link wouldnt work otherwise, since im using the classic site folder to store all the media, the problem starts here:
heres the path im working with:
/
/m
/public_html
the file in
/m/user/fnc/upload.php
is directed to save an img to
/public_html/photos/users/
here's a fragment of the code in upload.php
for the first line, I use a redirect variable called $img that leads to the index of the classic version, that would be
www.mysite.com/
so
$URL = $img.'photos/users/';
$NewFotoName = "misite_".$usuarioid."_".time().".jpg";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$imagen = $_POST['Imagen'];
if ( isset($_POST['Imagen']) ) {
$image = base64_decode($imagen);
$im = imagecreatefromstring($image);
imagepng($im,$URL.$NewFotoName);
imagedestroy($im);
$query = "UPDATE Utenti SET foto = '$NewFotoName' WHERE id_utente = ".$usuarioid;
$result = $mysqli->query($query);
if(!$result){die($mysqli->error);}
echo "index2.php";
die();
} else {
echo "index2.php";
die();
}
} else {
echo "index2.php";
die();
}
and i call it from a file one folder above it called index2.php with this code:
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'original'
}).then(function (resp) {
$('#imagebase64').val(resp);
var imagen_cortada = $('#imagebase64').val();
var base64image = imagen_cortada;
var parametros = { "Imagen" : base64image };
$.ajax({
data: { "Imagen" : output },
url: 'fnc/upload.php',
method: 'POST', // or GET
success: function(msg)
{
alert("Imagen subida con exito.");
alert(msg);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("Error al Subir la Imagen.");
alert(errorThrown);
window.location.replace(msg);
}
});
now when the form is submited I get a succes alert but in the "alert(msg);" I get an error that says
imagepng(path/to/the/file.png): failed to open stream; no such file or
directory in /home/mysite/m/user/fnc/upload.php
So the name of the file gets saved into the database but the file doesnt.
I appreciate any suggestions, excuse any spelling mistakes.
//edit
I found a work arround and moved the subdomaind directory inside public_html, had to learn a bit about the .htacces, it seems this way i will not have all those pesky permision problems
I found a work arround and moved the subdomaind directory inside public_html, had to learn a bit about the .htacces, it seems this way i will not have all those pesky permision problems, the other workarrounds posted in the similar thread Vic Seedoubleyew posted didnt seem to do the trick for me
I followed this tutorial on my vps: http://permadi.com/2010/10/html5-saving-canvas-image-data-using-php-and-ajax/
testSave.php
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// 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;
$randnum = rand(1111111111,9999999999);
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$tmpfname = tempnam("http://123.xx.xx.xx/test/tmp/", "FOO");
$fp = fopen(http://123.xx.xx.xx/test/test . uniqid() .".png","wb");
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
JS
function saveViaAJAX()
{
var testCanvas = document.getElementById("testCanvas");
var canvasData = testCanvas.toDataURL("image/png");
var postData = "canvasData="+canvasData;
var debugConsole= document.getElementById("debugConsole");
debugConsole.value=canvasData;
//alert("canvasData ="+canvasData );
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
//ajax.setRequestHeader('Content-TypeLength', postData.length);
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
//alert(ajax.responseText);
// Write out the filename.
document.getElementById("debugFilenameConsole").innerHTML="Saved as<br><a target='_blank' href='"+ajax.responseText+"'>"+ajax.responseText+"</a><br>Reload this page to generate new image or click the filename to open the image file.";
}
}
ajax.send(postData);
}
The problem is that when the user clicks 'send via ajax', there is no image sent/generated in the server directory(http://prntscr.com/8bhmxa). This is the outcome: http://prntscr.com/8bhi62 and everything in the directory remains unchanged.
What should happen is for a link of the image to be generated under the 'Saved as'
Any solutions?
P.S.
Is there anyway to echo the image link with php?
The problem is with your AJAX. Refer Url here the code is given for saving canvas with php and ajax.
Link
I am developing an application that use HTML and js for front-end and PHP for back-end. I have the following code which should have the functions that: 1, when click on the background image, user can choose photo from there phone as new background image, and use PHP to save the image on server and get the image path, store the path into database, then send new path back to front with JSON, and display the selected image as new background image. Thanks for any help.
javascript for sending and retrieve data:
function UploadImageDialog()
{
$("#newProfileImage").click();
}
function profileImageSelected(fileInput)
{
var xhr = new XMLHttpRequest();
xhr.open("POST", "UploadProfileImage.php", true);
var formData = new FormData();
formData.append("file", fileInput.files[0]);
xhr.send(formData);
xhr.onload = function() {
alert(xhr.responseText); //test the returned info from PHP.
if(xhr.responseText != ""){
$("#profileBackgroundImage").setAttribute("src", xhr.responseText);
}
else
{
alert("Your file failed to upload");
}
}
}
HTML code to call the javascript:
<div style="width:91.5vw;height:78.5vh;margin-top:10.5vh;">
<img class="backgroundImage" id="pictureSrc" src="img/Jenny.jpg" onclick="UploadImageDialog()" />
</div>
<input type="file" id="newProfileImage" style="display:none;" onchange="profileImageSelected(this)"/>
PHP code to get the path:
<?php
if(is_uploaded_file($_FILES['file']['tmp_name'])) // if user uploads file
{
if (!file_exists("./img/EventImages/" . $_FILES["file"]["name"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], "./img/EventImages/" . $_FILES["file"]["name"]))
{
echo "img/EventImages/" . $_FILES["file"]["name"];
}
}
else
{
echo "img/EventImages/" . $_FILES["file"]["name"];
}
}
?>
You should use some libraries like uploadify to upload files without posting form.
DEMO
I have figured that out. There was nothing wrong with the code, but I didn't set the Directory Permission correctly on the server.