New question

Question:

Date: 10-02-2020 22:17:56 (In Spanish)

Tengo problemas con la librería Dropzone al insertar imagen en la base de datos, el código que tengo es el siguiente[Unanswered]

Este es el código para insertar varias imágenes mediante dropzone que se llama imagenes_add_multiple.php y el siguiente se llama upload.php, alguien me pudiera ayudar, cuando abro el archivo imagenes_add_multiple.php me lista todas la imagenes correspondientes a una nota mediante el $refProducto = $_GET["recordID"], pero si agrego solo una imagen la graba en la base de datos y en la carpeta correspondiente mediante time() para que su nombre no se repita, el tema es cuando quiero insertar dos imágenes al mismo tiempo, graba una sola imagen en la carpeta, pero dos entradas en la base de datos con el mismo nombre, o sea lo duplica. Si me pudieran orientar, estaría muy agradecido, saludos a todos.

imagenes_add_multiple.php

<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "1,5,10";
$MM_donotCheckaccess = "false";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && false) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "../index.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?><?php require_once('../Connections/panel.php'); ?>

<!doctype html>
<html><!-- InstanceBegin template="/Templates/panel.dwt.php" codeOutsideHTMLIsLocked="false" -->
<head>
<meta charset="utf-8">
<!-- InstanceBeginEditable name="doctitle" -->
<title>Administracion Principal</title>
<!-- InstanceEndEditable -->
<!-- InstanceBeginEditable name="head" -->
<!-- InstanceEndEditable -->
<?php include("../includes/estilos.php"); ?>

<link rel="stylesheet" href="../css/dropzone.css" type="text/css">
<style>
    .wrapper{
      margin-top:2%;
    }
    .dropzone .dz-preview .dz-image img{
      width:100%;
    }
</style>
		</head>
		<body>

        <div class="container-fluid">
          <div class="row">
                <?php include("../includes/encabezado.php"); ?>
          </div>
          <div class="container-fluid">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
              <div class="row">
               <hr class="hr">
              </div>
            </div>
          </div>
          <div class="container-fluid">
            <div class="row">		      
			  <div class="col-xs-12 col-sm-10 col-md-10 col-lg-2">
			  <?php include("../includes/cabeceraadmin.php"); ?>
			  </div>
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-10">
 
        <!--editable--> 
        <!-- InstanceBeginEditable name="Contenido" -->
    <h1 class="titulo">Agregar Imagen</h1><h4>A la nota: <?php echo ObtenerTitulodeidNoticias($_GET["recordID"]) ?></h4>
    <p>&nbsp;</p>
<div class="wrapper">
  <div class="container">
      <hr class="my-4">

      <!-- Change /upload-target to your upload address -->
      <form id="frmdropzone" action="#" class="dropzone"></form>
      <div class="text-center mt-3">
        <button type="button" id="btnsubmit" class="btn btn-success btn-md btn3d"><i class="fa fa-upload"></i> Insertar Imagen(es)</button>
       </div>

</div>
</div>
    
      <input type="hidden" name="refProducto" value="<?php echo $_GET["recordID"]; ?>" />
 
    <p>&nbsp;</p><!-- InstanceEndEditable --> 
        <!-- end editable --> 
      </div>
    </div>
  </div>
  <!--footer-->
  <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
    <p>
    <div class="footer" onClick="window.open('http://www.ocssoftware.com.ar','_blank'); ">
      </p>
      <!-- end .footer --></div>
  </div>
  <!-- end .container --> 
</div>
     <?php include("../includes/js.php"); ?>

<script type="text/javascript">
(function($) {


Dropzone.autoProcessQueue = false; //Configuración de Dropzone para que el archivo no se cargue automáticamente
Dropzone.autoDiscover = false; //Configuración de Dropzone para que el archivo no se cargue automáticamente

var myDropzone = new Dropzone('#frmdropzone', {
    url: "upload.php?recordID=<?php echo $_GET["recordID"]; ?>",
    autoProcessQueue: false,
    parallelUploads: 10, //número máximo de cargas
    uploadMultiple: false,
    maxFilesize: 20, //tamaño de archivo 2MB
    addRemoveLinks: true,
    acceptedFiles:'image/jpeg,image/png,image/jpg',
    init: function() {
        thisDropzone = this;
        this.on("uploadprogress", function(file, progress) {
            console.log("File progress", progress);
        });
        this.on("complete", function(file) {
          //mensaje si la carga se realizó correctamente
        });


    },
    //Eliminar archivos de la base de datos usando ajax
    removedfile: function(file) {
        var name = file.name; 
        var id = file.id; 
        if (confirm("Estás seguro de eliminar la imagen?")) {
            /*$.ajax({
                type: 'POST',
                url: 'delete.php',
                data: {id: id, name: name},
                sucess: function(data){
                    console.log('success: ' + data);
                    alert('La imagen ha sido eliminada');
                }
            });*/
            var ref;
            if((ref = file.previewElement) != null){
                return ref.parentNode.removeChild(file.previewElement);
            
            }
            return false;
        }
    },
});

$("#btnsubmit").on("click", function(e) {
  //Función para subir imágenes a la base de datos
  if (myDropzone.getQueuedFiles().length > 0) {
      myDropzone.processQueue();
  }
  $('#frmdropzone').submit();
  alert('Imagen cargada correctamente');
  window.location.href="imagenes_lista.php?recordID=<?php echo $_GET["recordID"]; ?>";
  return false;

});

})(jQuery)
</script>
</body>
<!-- InstanceEnd --></html>



upload.php
<?php
include "conexion.php";


if (!empty($_FILES)) {
	
function resize($source_image, $destination, $tn_w, $tn_h, $quality = 100, $wmsource = false)
{
    $info = getimagesize($source_image);
    $imgtype = image_type_to_mime_type($info[2]);

    #assuming the mime type is correct
    switch ($imgtype) {
        case 'image/jpeg':
            $source = imagecreatefromjpeg($source_image);
            break;
        case 'image/gif':
            $source = imagecreatefromgif($source_image);
            break;
        case 'image/png':
            $source = imagecreatefrompng($source_image);
            break;
        default:
            die('Invalid image type.');
    }

    #Figure out the dimensions of the image and the dimensions of the desired thumbnail
    $src_w = imagesx($source);
    $src_h = imagesy($source);


    #Do some math to figure out which way we'll need to crop the image
    #to get it proportional to the new size, then crop or adjust as needed

    $x_ratio = $tn_w / $src_w;
    $y_ratio = $tn_h / $src_h;

    if (($src_w <= $tn_w) && ($src_h <= $tn_h)) {
        $new_w = $src_w;
        $new_h = $src_h;
    } elseif (($x_ratio * $src_h) < $tn_h) {
        $new_h = ceil($x_ratio * $src_h);
        $new_w = $tn_w;
    } else {
        $new_w = ceil($y_ratio * $src_w);
        $new_h = $tn_h;
    }

    $newpic = imagecreatetruecolor(round($new_w), round($new_h));
    imagecopyresampled($newpic, $source, 0, 0, 0, 0, $new_w, $new_h, $src_w, $src_h);
    $final = imagecreatetruecolor($tn_w, $tn_h);
    $backgroundColor = imagecolorallocate($final, 255, 255, 255);
    imagefill($final, 0, 0, $backgroundColor);
    //imagecopyresampled($final, $newpic, 0, 0, ($x_mid - ($tn_w / 2)), ($y_mid - ($tn_h / 2)), $tn_w, $tn_h, $tn_w, $tn_h);
    imagecopy($final, $newpic, (($tn_w - $new_w)/ 2), (($tn_h - $new_h) / 2), 0, 0, $new_w, $new_h);

    #if we need to add a watermark
    if ($wmsource = '../../imagenes/noticias/watemark.gif') {
        #find out what type of image the watermark is
        $info    = getimagesize($wmsource);
	$imgtype = image_type_to_mime_type($info[2]);

        #assuming the mime type is correct
        switch ($imgtype) {
            case 'image/jpeg':
                $watermark = imagecreatefromjpeg($wmsource);
                break;
            case 'image/gif':
                $watermark = imagecreatefromgif($wmsource);
                break;
            case 'image/png':
                $watermark = imagecreatefrompng($wmsource);
                break;
            default:
                die('Invalid watermark type.');
        }

        #if we're adding a watermark, figure out the size of the watermark
        #and then place the watermark image on the bottom right of the image
        $wm_w = imagesx($watermark);
        $wm_h = imagesy($watermark);
		
        imagecopy($final, $watermark, $tn_w - $wm_w, $tn_h - $wm_h, 0, 0, $tn_w, $tn_h);

    }
    if (imagejpeg($final, $destination, $quality)) {
        return true;
    }
    return false;
}


$nombre_nuevo = time().'.jpg';
$carpeta = '../../imagenes/noticias/';

$refProducto = $_GET["recordID"];
    $errors     = array();
    $maxsize    = 209715200; //20MB convert jadi byte
    $acceptable = array(
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );

    if(($_FILES['file']['size'] >= $maxsize) || ($_FILES["file"]["size"] == 0)) {
        $errors[] = 'Archivo demasiado grande. El archivo debe tener menos de 20 megabytes.';
    }

    if(!in_array($_FILES['file']['type'], $acceptable) && (!empty($_FILES["file"]["type"]))) {
        $errors[] = 'Tipo de archivo invalido. Solo se aceptan los tipos PDF, JPG, GIF y PNG.';
    }

    if(count($errors) === 0) {

		if(move_uploaded_file ($_FILES['file']['tmp_name'], $_FILES['file']['name']))
				{	resize($_FILES['file']['name'],$carpeta.$nombre_nuevo,700,414,50);
					$ok_image = true;
				}


        $image_name = $nombre_nuevo;
        $mysqli->query("INSERT INTO tblimagenes (refProducto,strImagen,intOrden) VALUES ('$refProducto','$image_name','1')");

        $result = array('status'=> 'sucesss');
        header('Content-type: text/json');             
        header('Content-type: application/json');
        echo json_encode($result);

    } else {
        foreach($errors as $error) {
            echo '<script>alert("'.$error.'");</script>';
        }
        die(); 
    }

} else { 
    $result = array('status'=> 'error');
    header('Content-type: text/json');             
    header('Content-type: application/json');
    echo json_encode($result);

}
?>


Creo que el problema es jquery, pero no se como solucionarlo
Tags: JQuery - PHP - PHP MySQLi Votes: 0 - Answers: 0 - Views: 6 Share on: Google Facebook Twitter LinkedIn Link
 

Answers:

No replies for this question, be the first to answer.
To actively participate in the community first must authenticate, enter the system.Sign In