Rename file with DropZoneJS when upload succesfull - dropzone.js

I've been trying all answer founding in the net and that never work, i would like that the file who is save in the PDF folder and in the database behind a choose name while uploading.
This is my code :index.php
upload.php

INDEX.PHP:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="widht=device-widht, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Glisser-deposer </title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/dropzone.css">
</head>
<body>
<div id="main">
<div id="header">
<h1> Glisser-deposer les fichiers de telechargement<br> </h1>
</div>
<div id="content">
<form class="dropzone" id="file_upload"></form>
<button id="upload_btn">telechargement</button>
</div>
</div>
<script type="text/javascript" src="js/dropzone.js" ></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
Dropzone.autoDiscover = false;
$(document).ready(function () {
$(".dropzone").dropzone({
renameFilename: function (filename) {
return new Date().getTime() + '_' + filename;
}
});
});
var myDropzone = new Dropzone("#file_upload", {
url: "upload.php",
parallelUploads: 3,
uploadMultiple: true,
acceptedFiles: '.pdf',
clickable: true,
autoProcessQueue: false,
renameFilename: function (filename) {
name = new Date().getTime() + '-' + filename;
return name;
},
success: function(file,response){
if(response == 'true'){
$('#content .message').hide();
$('#content').append('<div classe="message success">Fichier Telecharger avec
succes.</div>');
}else{
$('#content').append('<div classe="message error">Le fichier ne peux etre
telecharger.</div>');
}
}
});
$('#upload_btn').click(function(){
myDropzone.processQueue();
});
</script>
</body>
</html>
UPLOAD.PHP :
<?php
/* Créer une connexion*/
$conn = mysqli_connect("localhost", "root", "","intranet"); // ("nom d'hôte", "nom
d'utilisateur", "mot de passe", " nom de la base")
/* Vérifier la connexion*/
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if($_FILES['file']['name'] != ''){
$file_names = '';
$total = count($_FILES['file']['name']);
for($i=0; $i<$total; $i++){
$filename = $_FILES['file']['name'][$i]; // Obtenez le nom du fichier
téléchargé.
$extension = pathinfo($filename,PATHINFO_EXTENSION); //Obtenez l'extension du
fichier téléchargé
$valid_extensions = array('pdf','.txt');
if(in_array($extension, $valid_extensions)){ // vérifier si le fichier de
téléchargement est un fichier pdf valide.
$new_name = rand() . ".". $extension;
$path = "PDF/" . $new_name;
move_uploaded_file($_FILES['file']['tmp_name'][$i], $path);
$file_names .= $new_name . " , ";
}else{
echo 'false';
}
}
// Enregistrer le nom des fichiers téléchargées dans la base de données
$sql = "INSERT INTO fichier VALUES('{$file_names}')";
if(mysqli_query($conn,$sql)){
echo 'true';
}else{
echo 'false';
}
}
?>

Related

Undefined property: Main::$upload , Codeigniter

I am trying to upload single image using codeigniter. But getting error
"Undefined property: Main::$upload
Filename: controllers/Main.php
Line Number: 14"
This is my controller file "controller/Main.php"
<?php
class Main extends CI_Controller
{
public function index(){
$this->load->view('main_view', array('error' => ''));
}
public function upload(){
$config['upload_path'] = "./images/";
$config['allowed_types'] = 'jpg|png|gif';
$this->load->initialize('upload', $config);
if(!$this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('main_view', $error);
}
else {
$file_data = $this->upload->data();
$data['img'] = base_url().'/images/'.$file_data['file_name'];
$this->load->view('success_msg', $data);
}
}
}
?>
and this is my view file "views/main_view.php"
<!DOCTYPE html>
<html>
<head>
<title>Image</title>
</head>
<body>
<?php echo $error; ?>
<?php echo form_open_multipart('main/upload');?>
<input type="file" name="userfile" />
<input type="submit" name="Submit" value="upload image"/>
</form>
</body>
</html>
when image upload is successful I'm trying to show the image by this "view/success_msg.php"
<!DOCTYPE html>
<html>
<head>
<title>Image</title>
</head>
<body>
<h1>File has been uploaded.</h1>
<img src="<?php $img?>" width="300" height="300">
</body>
</html>
my image folder name is "images" and it is in the root directory. Please help my why I am having this error ?
Maybe the upload library isn't loaded. Change the first few lines ofpublic function upload() to the following
public function upload(){
$config['upload_path'] = "./images/";
$config['allowed_types'] = 'jpg|png|gif';
$this->load->library('upload', $config);
By sending $config to load->library you do not need to use initialize().
Controller
public function upload(){
$cc = $_FILES['userfile']['name'];
$extension = pathinfo($cc, PATHINFO_EXTENSION);
$newfile = preg_replace('/[^A-Za-z0-9]/', "", $_FILES["userfile"]['name']);
$config['file_name'] = time() . $newfile;
$ss = ".";
$picture1 = time() . $newfile . $ss . $extension;
$config['upload_path'] = "./images/";
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
echo $this->upload->display_errors();
} else {
$this->load->view('success_msg', $picture1 );
}
}
View page
<!DOCTYPE html>
<html>
<head>
<title>Image</title>
</head>
<body>
<?php echo $error; ?>
<?php echo form_open_multipart('main/upload');?>
<input type="file" name="userfile" />
<input type="submit" name="Submit" value="upload image"/>
</form>
</body>
</html>
view/success_msg.php
<!DOCTYPE html>
<html>
<head>
<title>Image</title>
</head>
<body>
<h1>File has been uploaded.</h1>
<img src="<?php $picture1 ?>" width="300" height="300">
</body>
</html>

Laravel 5.2 ajax code doesn't work

I developed a simple ajax code.According to this image when click+ qty increase and when click - qty decrease
Code in online _help.blade.php
<head>
<title>Ajax Example</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script>
$(document).ready(function(){
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
var increment = $(this).data('increase');
var itemId = $('.cart_quantity_input').val();
$.ajax({
type:'post',
url:'getmsg',
dataType:'json',
data:{
'item_id': itemId,
'increase': increment
},
success:function(data){
$("cart_quantity_input").val(data.qty);
} });
});
});
</script>
</head>
<body>
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="javascript:void(0)" data-increase="1" > + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{1}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href="javascript:void(0)" data-increase="0" > - </a>
</div>
</body>
<footer>
<script type="text/javascript">
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {"X-CSRF-TOKEN": csrf_token}
});
</script>
</script>
</footer>
Code in controller function
public function ajaxl(Request $request)
{
if ($request->ajax()) {
$id = $request->item_id;
if ($request->increase) {
//$cart->increment('qty');
$qty = 2;
} else {
//$cart->decrement('qty');
$qty = 0;
}
//echo"hello ajaxlara:";
return response()->json(array('qty'=> $id), 200);
}
}
And this routes.php
Route::get('/ajax',function(){return view('online_help');});
Route::post('/getmsg','Hello#ajaxl');
When I click + or - the value doesn't change and no error.
Please any one help me
The problem is very small.
This line:
$("cart_quantity_input").val(data.qty);
just you forgot to add . before cart_quantity_input
So change it to be :
$(".cart_quantity_input").val(data.qty);

How to Save File with time as name and return time value with uploadify

what i intend to do, is to use uploadify to upload a file, change its name in uploadify.php for the value of time() ,save it , and return the name of the saved file back to the HTML, im not sure how to do it, currently im using this as guide
http://www.uploadify.com/documentation/uploadify/customizing-the-server-side-upload-script/
and this is my code so far
index.php
'<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript"></script>
<script src="jquery.uploadify.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="uploadify.css">
<style type="text/css">
body {
font: 13px Arial, Helvetica, Sans-serif;
}
</style>
</head>
<body>
<form>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file" multiple="true">
</form>
<script type="text/javascript">
<?php $timestamp = time();?>
$(function() {
$('#file_upload').uploadify({
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('unique_salt' . $timestamp);?>',
'name' : 'somename'
},
'method' : 'post',
'swf' : 'uploadify.swf',
'uploader' : 'uploadify.php',
onUploadComplete : function(data, file , response){
alert('The file was saved to: ' + data);
alert(response);
}
});
});
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
var img = 'localhost/uploads/'+ $("#hidden").val;
var cuenta_sap = $("#cuenta_sap").val();
var ubicacion = $("#ubicacion").val();
var codigo_centro_beneficio = $("#codigo_centro_beneficio").val();
var nombre = $("#nombre").val();
var proyecto = $ ("#proyecto").val();
var departamento = $ ("#departamento").val();
var tipo_activo = $("#tipo_activo").val();
var proveedor = $("#proveedor").val();
var modelo = $("#modelo").val();
var numero_serie = $("#numero_serie").val();
var marca = $ ("#marca").val();
var numero_remision = $("#numero_remision").val();
var myData ='cuenta_sap='+ cuenta_sap + '&ubicacion='+ ubicacion +
'&codigo_centro_beneficio='+ codigo_centro_beneficio + '&nombre=' + nombre + '&proyecto='
+ proyecto + '&departamento='+ departamento + '&tipo_activo=' + tipo_activo
+'&proveedor='+ proveedor +'&modelo=' + modelo + '&numero_serie=' + numero_serie +'&marca='
+ marca + '&numero_remision='+ numero_remision;
e.preventDefault();
if(cuenta_sap==''||ubicacion==''||codigo_centro_beneficio==''
||nombre==''||proyecto==''||departamento
==''||tipo_activo==''||proveedor==''||modelo==''
||numero_serie==''||marca==''||numero_remision=='')
{
alert("Formato incompleto!");
return false;
}
$("#FormSubmit").hide(); //hide submit button
$("#LoadingImage").show(); //show loading image
$.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //
success:function(result){
$("#responds").delay(10000).fadeIn();
$("#responds").append("<li class='res'>"+result+"</li>");
$('.res').remove();
$("#proyecto").val(''); //empty text field on successful
$("#departamento").val(''); //empty text field on successful
$("#tipo_activo").val(''); //empty text field on successful
$("#modelo").val(''); //empty text field on successful
$("#numero_serie").val(''); //empty text field on successful
$("#marca").val(''); //empty text field on successful
$("#numero_remision").val(''); //empty text field on successful
$("#cuenta_sap").val(''); //empty text field on successful
$("#ubicacion").val(''); //empty text field on successful
$("#nombre").val(''); //empty text field on successful
$("#codigo_centro_beneficio").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
$('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
$(this).hide(); //hide currently clicked delete button
$.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut();
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
</script>
<div class="content_wrapper" id="wrapepr">
<div class="form_style">
<input name="hidden" id="hidden" type="text"></input>
<br>
<a>Datos</a>
<br>
<input name="cuenta_sap" id="cuenta_sap" placeholder="cuenta sap" class="input"></input>
<select name="departamento" class="input" id="departamento">
<option value = "">seleccione departamento</option>
<?php
include("db.php");
$stmt = $db->prepare("SELECT `id`, `departamento` FROM `departamentos`");
$stmt->execute();
$stmt->bind_result($id,$departamento);
while ($stmt->fetch()){
echo "<option value='$id'>$departamento</option>";
}
?>
</select>
<select name="proyecto" class="input" id="proyecto" >
<option value = "" >seleccione proyecto</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`proyecto` FROM `proyectos`");
$stmt->execute();
$stmt->bind_result($id,$proyecto);
while ($stmt->fetch()){
echo "<option value='$id'>$proyecto</option>";
}
?>
</select>
<select name="tipo" class="input" id="tipo_activo">
<option value = "" class="input" >tipo de activo</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`tipo` FROM `tipo_activo`");
$stmt->execute();
$stmt->bind_result($id,$tipo_activo);
while ($stmt->fetch()){
echo "<option value='$id' class='input'>$tipo_activo</option>";
}
?>
</select>
<select name="proveedor" class="input" id="proveedor">
<option value = "" class="input" >seleccione proveedor</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`nombre` FROM `proveedores`");
$stmt->execute();
$stmt->bind_result($id,$nombre);
while ($stmt->fetch()){
echo "<option value='$id' class='input'>$nombre</option>";
}
?>
</select>
<input name="codigo_centro_beneficio" id="codigo_centro_beneficio" placeholder="codigo centro
beneficio" class="input"></input>
<input name="nombre" id="nombre" placeholder="nombre" class="input"></input>
<input name="modelo" id="modelo" placeholder="modelo" class="input"></input>
<input name="numero_serie" id="numero_serie" placeholder="numero_serie" class="input">
</input>
<input name="marca" id="marca" placeholder="marca" class="input"></input>
<input name="numero_remision" id="numero_remision" placeholder="numero remision" class="input">
</input>
<input name="upload" id="upload" class="input" type="file"></input>
<button id="FormSubmit">registrar</button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</div>
<ul id="responds" >
</ul>
</div>
</body>
</html>'
and uploadify.php
'
$targetFolder = '/uploads'; // Relative to the root
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$now = time();
$name = $_POST('name')FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
echo rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
if(file_exists($targetFile)){
++$now;
$targetFile = rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
$name $targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
echo $name;
}
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
}
else {
echo 'Invalid file type.';
}
?>'
I found the answer to this, after a while of searching and reading uploadify manuals, it turns out if you use onUploadComplete, and you just upload one single fine, the method will never excecute, and it will keep waiting for more files, instead for one file only, you have to use onUploadSuccess, and read the data returned by it using file,data,response as parameters.

How to save a image coded in Data-URI?

I'm trying to find a trick to save a picture coded in Data-URI like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA1MAAAE7CAYAAAA4gNuCAAAgAElEQ…
i/fPjJwSa8k8blB7TPIbffod14w9E/Baq03hUCXPf2/wK6K8SbNo44VwAAAABJRU5ErkJggg==
Another question: Where the picture is saved in the first time in the server? Browser?
JS: save image to user's disk using javascript,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
window.onload = function () {
var img = document.getElementById('embedImage');
var button = document.getElementById('saveImage');
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA'+
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO'+
'9TXL0Y4OHwAAAABJRU5ErkJggg==';
img.onload = function () {
button.removeAttribute('disabled');
};
button.onclick = function () {
window.location.href = img.src.replace('image/png', 'image/octet-stream');
};
};
</script>
</head>
<body>
<img id="embedImage" alt="Red dot"/>
<input id="saveImage" type="button" value="save image" disabled="disabled"/>
</body>
</html>
PHP: http://j-query.blogspot.com/2011/02/save-base64-encoded-canvas-image-to-png.html
<?php
// requires php5
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
EDIT JS solution 2 (fiddle: http://jsfiddle.net/KAdN8/):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
var img = document.getElementById('embedImage');
if( document.createEvent ) {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'click', true, false );
img.dispatchEvent(evObj);
} else if( document.createEventObject ) {
img.fireEvent('on'+evt);
}
</script>
</head>
<body>
Download
</body>
</html>

Getting "SyntaxError: JSON.parse: unexpected character" When aparently the response is correct

I'm crazy with this error, I'm traying to make an Ajax login form, this is my code:
My HTML:
<div id='login-box' name='login-box' class='radius-all-tiny'>
<div class='bt-wrapper bt-wrapper-hover'>
<span class='bt-icon bt-icon-hover btn-users'></span>
</div>
<div id='login-banner' name='login-banner'>
" . $content['SESSION_BANNER'] . "
</div>
<div class='radius-all-tiny' id='login-error' name='login-error'>
</div>
<form id='login-frm' name='login-frm' method='post' action='./'>
<input type='text' id='usuario' name='usuario' placeholder='" . $content['SESSION_USER'] . "' />
<input type='password' id='contrasena' name='contrasena' placeholder='" . $content['SESSION_PASS'] . "' />
<div class='submit-wrap'><input class='bt-submit radius-all-medium' type='submit' id='enviar' name='enviar' value='" . $content['CONTACT_FRM_SEND'] . "' /></div>
</form>
</div>
My JS:
<script type='text/javascript'>
$(document).ready(function() {
// FORCE BROWSER NOT CACHE AJAX CALLS
$.ajaxSetup({ cache: false });
// HIDE ERROR DIALOG
$('#login-error').hide();
// LOGIN/OUT BUTTON BEHAVIOR
$('#bt-login').click(function(){
$('#login-error').hide();
$.fancybox.open({
href : '#login-box',
padding : 0,
onClosed : function() { }
});
});
// LOADING ANIMATION
var ajaxload = '<img src=\"../img/components/spinner-dark.gif\" alt=\"" . $content['MAIN_LOADING'] . "\" />';
$('#login-frm').bind('submit', function(){
// AUTHENTICATING...
// VALIDAMOS QUE NO HAYAN CAMPOS VACÍOS
if (($('#usuario').val().length < 1) || ($('#contrasena').val().length < 1))
{
$('#login-error').html('EMPTY');
$('#login-error').show();
return false;
}
// SI NO ESTÁN VACÍOS LOS CAMPOS, ENTONCES VALIDAMOS...
$.ajax({
type: 'POST',
cache: false,
url: '../libs/class.log.in.out.php',
data: {usuario: $('#usuario').val(), contrasena: $('#contrasena').val()},
dataType: 'json',
success: function(data)
{
if (data.success)
{
// ESCRIBIMOS LA VARIABLE DE SESIÓN
// CERRAMOS FANCYBOX
$.fancybox.close();
// RECARGAMOS LA PÁGINA PRINCIPAL
document.location.href = $('#urlactual');
}
else
{
// MOSTRAMOS ERROR DE AUTENTICACIÓN
$('#login-error').html('FAILED_AUTH');
$('#login-error').show();
}
}
});
return false;
});
});
</script>
My class.log.in.out.php:
/////////////////////////////////////////////////
// TRANSPORTADOR DE DATOS
/////////////////////////////////////////////////
$data = array(
'success' => false,
'msg' => 'No se encontró ningún dato...'
);
// SOLICITAMOS LOS VALORES DE CONEXIÓN
$usr = (isset($_REQUEST['usuario']) ? $_REQUEST['usuario'] : 'NULL');
$pwd = (isset($_REQUEST['contrasena']) ? $_REQUEST['contrasena'] : 'NULL');
// VALIDAMOS LOS DATOS
class_exists('Database') || require ('class.database.php');
$resp = "";
$thisstt = false;
// INSTANCIAMOS LA CLASE DE BASE DE DATOS
$dbs = new Database();
$datos = $dbs->logIn($usr, $pwd, "", $thisstt);
if ($thisstt)
$resp = $datos['usuario'];
else
$resp = "" . $datos['error'] . " Usuario: " . $usr . "";
// DEVOLVEMOS EL ESTADO DE LA VALIDACIÓN
$data = array(
'success' => $thisstt,
'msg' => utf8_encode($resp)
);
/////////////////////////////////////////////////
// EMPAQUETADO DE DATOS
/////////////////////////////////////////////////
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($data);
I receive this response from de class.log.in.out.php (Using Firefox's developer tools):
When the authentication fail:
{"success":false,"msg":"Los datos ingresados son incorrectos... Usuario: 123"}
When the authentication is correct:
{"success":true,"msg":"gchinchilla"}
But Firefox says that the Syntax is incorrect, could you help me?
I apologize for my bad english, I'm learning it...
i do not see any need of converting array to object for json_encode.
i will suggest using :
echo json_encode($data);
instead of :
echo json_encode((object)$data);
SOLVED! There was an "codification error", I have converted the PHP file from UTF-8 to UTF-8 Without BOM.
More info here: http://es.wikipedia.org/wiki/UTF-8#Byte_order_mark_.28BOM.29

Resources