Uploadify - onComplete || onAllComplete not work - javascript

I know there are already some threads with this question, but none was helpful to me.
I have an image manager and I would like to reload the page with "onComplete" event, but it not work for me.
you can see an example: http://graficnova.com/uploadifytest/imgLoader.php
Everything works successful!!, but u need press f5 key for refresh it :(.
Thx and sorry for my english!
code:
head:
<script type="text/javascript">
$(function() {
$("#fileInput").uploadify({
width : 100,
swf : 'swf/uploadify.swf',
uploader : 'php/uploadify.php',
queueID : 'imgloadList',
oncomplete : function() {
alert('hello world?'); //<- THIS NOT WORK
}
});
});
</script>
php: uploadify.php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
//$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetPath = 'xxxxx/xxxx/xxxx/xxxx';
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo '1'; //<- return response
} else {
echo 'Invalid file type.'; //<- return response
}
}

Based on the Uploadify docs, there isn't an onComplete event, but there is an 'onUploadComplete' event:
Triggered once for each file when uploading is completed whether it was successful or returned an error. If you want to know if the upload was successful or not, it’s better to use the onUploadSuccess event or onUploadError event.
Might want to give that a try. Or check out onQueueComplete.

Related

Issues in image uploading using vue-wysiwyg

I am using vue-wysiwyg editor in my laravel-vue application. In this editor there is an option to upload images and through incomplete documentation of this package I am able to upload the image and get public url of the uploaded file. But this package works sometimes and does not work at all sometimes.
Here is how I am using this package
main.js
import wysiwyg from "vue-wysiwyg";
Vue.use(wysiwyg, {
forcePlainTextOnPaste: true,
image: {
uploadURL: "/api/save-support-files",
dropzoneOptions: {}
},
});
/api/save-support-files
public function uploadUserFile(Request $request)
{
$uploadedFile = $request->file('file');
if (false == $uploadedFile) {
return response()->api(false, 'Kindly upload a file');
}
$allowed_file_extentions = [
'jpeg',
'png',
'jpg',
'gif',
'svg'
];
if (false == in_array($uploadedFile->getClientOriginalExtension(), $allowed_file_extentions)) {
return response()->api(false,'Allowed file types are jpeg, png, jpg, gif, svg',null);
}
$file_url = Storage::disk('public')->putFileAs('/support-files',$uploadedFile,generateRandomString('5').'.'.$uploadedFile->getClientOriginalExtension());
// return response()->api(true,'File uploaded successfully',config('app.url').'/storage/'.$file_url);
return config('app.url').'/storage/'.$file_url;
}
Issues I am facing right now:
As soon as I select image from file browser, image is uploaded through api successfully but it is not showing in editor.
Unable to select already uploaded image, I have to refresh the page and then again select file to upload it again.
Is anyone having solution to this problem ? Kindly help me out.
my upload store function look like this:
public function store(Request $request)
{
$request->validate(['file' => 'required']);
$file = $request->file('file');
if ($file->isValid()) {
$path = $file->storePublicly(now()->format('Y' . DIRECTORY_SEPARATOR . 'm' . DIRECTORY_SEPARATOR . 'd'));
return response(Storage::disk('public')->url($path), Response::HTTP_CREATED)->withHeaders(
[
'content-type' => 'text/html'
]
);
}
abort(Response::HTTP_BAD_REQUEST);
}
make sure you have set APP_URL in .env to full url (http://my-site.com)
make sure you run php artisan storage:link

Save JS data in Ajax

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)

jQuery File Upload not Uploading

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.

Froala - image upload JSON response

I am using Froala editor for my website. This editor have built in image upload function - image upload is working fine, but I am having trouble with response.
This is from the documentation:
The server processes the HTTP request.
The server has to process the upload request, save the image and return a hashmap containing a link to the uploaded image. The returned hashmap needs to look like: { link: 'path_to_uploaded_file/file.png' }
This is my function for returning link:
public function froala_upload()
{
header('Content-type: application/json');
$folder = 'public/img/media';
$slika = $this->site->single_upload($folder, 'jpg|jpeg|png|bmp|JPG|JPEG|PNG|BMP');
$link = array("link" => $slika);
echo json_encode($link);
}
This is JS code:
$('textarea').editable({
inlineMode: false,
imageUploadParam: "userfile",
imageUploadURL: "<?php echo base_url() ?>admin/froala_upload",
// Set the image error callback.
imageErrorCallback: function (data) {
// Bad link.
if (data.errorCode == 1) {
console.log(data);
}
// No link in upload response.
else if (data.errorCode == 2) {
console.log(data);
}
// Error during file upload.
else if (data.errorCode == 3) {
console.log(data);
}
}
});
When I upload image I get following error:
Object { errorCode=1, errorStatus="Bad link."}
And this is response that I get:
{"link":"7d59d61.jpg"}
What seem to be a problem?
Froala image upload documentation
You must return the absolute image path :
$link = array("link" => '/img/media/'.$slika);
Because Froala looks for it to http://example.com/7d59d61.jpg
The problem is that the image cannot be loaded from the returned link. You'd have to make sure that the image can be accessed from it. Froala Editor uses the link you return for src attribute from img tag. I think you'd have to do something like:
$link = array("link" => $slika . 'public/img/media');

No way to pass data using form with Uploadify

sorry if I am being redundant but I've tried every single example I found here and on google :D
What I am trying to do is on the upload of image, what was typed on inputbox will be send along to the uplodify.php where my insert is. My problem is, name of picture has being saved to the mysql but what was typed on the textfield dont.
Would you guys let me know what is going on?
This is the part of my code
'multi' : true,
'auto' : false,
'onUploadStart' : function(file) {
$("#file_upload").uploadify('settings', 'formData', {'galeria': $('#galeria').val()});
},
<form id="form1" name="form1" action="">
<p>
<input type="file" id="file_upload" name="file_upload" />
<br>
<br>
Galeria<br>
<label>
<input type="text" name="galeria" id="galeria">
uplodify.php
$galeria = $_POST['galeria'];
$regiao = $_POST['regiao'];
if (!empty($_FILES)) {
$img = $_FILES['Filedata']['name'];
$ext = substr($img, -4);
$img = md5($img).date("dmYHis").$ext;
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $img;
$adicionar = mysql_query ("INSERT INTO imagens (foto, galeria, regiao) VALUES('$img','$galeria','$regiao')");
// $fileTypes = str_replace('*.','',$_REQUEST['fileext']);
// $fileTypes = str_replace(';','|',$fileTypes);
// $typesArray = split('\|',$fileTypes);
// $fileParts = pathinfo($_FILES['Filedata']['name']);
// if (in_array($fileParts['extension'],$typesArray)) {
// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);
move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
// } else {
// echo 'Invalid file type.';
// }
}
Try changing your onUploadStart method to extend the uploadify formData property like this:
onUploadStart: function ( file ) {
var $fileUpload = $('#file_upload')
, formData = $fileUpload.uploadify('settings', 'formData')
, newFormData = $.extend({}, formData, { galeria: $('#galeria').val() });
$fileUpload.uploadify('settings', 'formData', newFormData);
}
I finally managed to made it work
This is the code I used
$('#file_upload').attr('file_upload', response).show();
$.post("insert2.php",{name: fileObj.name, galeria: $("#galeria").val(), regiao: $("#regiao").val()}, function(info) {
alert(info); // alert UPLOADED FILE NAME
});
}
});
Now I have a different problem lol it always show right...
Since the code to save the file on dabase is on insert2.php and the code to rename the picture inside the uploadify.php. How can I save the new name on the database instead the name of file I uploaded?
Another question.... is that a way to generate a thumbnail based on those pictures on database?

Categories