Foros del Web » Programando para Internet » Javascript » Frameworks JS »

Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Estas en el tema de Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo en el foro de Frameworks JS en Foros del Web. Hola. Quería dejar por aquí un ejemplo de cómo subir, reducir y mostrar en vista previa una imagen de un formulario html dinámicamente con Ajax. ...
  #1 (permalink)  
Antiguo 24/05/2009, 15:43
 
Fecha de Ingreso: mayo-2009
Ubicación: Madrid, España
Mensajes: 9
Antigüedad: 14 años, 11 meses
Puntos: 11
Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Hola.

Quería dejar por aquí un ejemplo de cómo subir, reducir y mostrar en vista previa una imagen de un formulario html dinámicamente con Ajax. En realidad no es con Ajax, porque JavaScript no puede manipular un campo archivo (tipo "file"), así que tiene que ser dinámicamente con php.

JavaScript no puede recoger el archivo seleccionado de un campo archivo para enviarlo dinámicamente por motivos de seguridad. La única manera de enviar un archivo es enviar el formulario completo con "submit". Para no enviar el archivo con el resto de los datos del formulario, el campo archivo debe ser un formulario separado del resto de los datos. Así puede enviarse automáticamente cada vez que se seleccione un nuevo archivo, sin afectar al resto de los campos. El archivo seleccionado se envía a un script php que evalúa si es un archivo de imagen válido, y, de ser así, lo sube, redimensiona y devuelve a la página html, a un iframe que muestra la imagen sin recargar la página.

De esta manera, ya se puede enviar con Ajax el resto de los datos del formulario, juntamente con una variable que el script php ha almacenado en el iframe, que contiene la ruta de la imagen subida en el servidor. Se envía a otro scrip php que procesa todos los datos, todo sin tener que recargar la página en ningún momento.

En total se usan un archivo html y dos php (en el siguiente post), que no suman más de 20 KB.

¿Qué os parece el sistema?

Saludos.


Código HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
Author: Alberto Moyano Sánchez
Date: 2009-05-24
Description: [...]
Notes and improvements: [...]
-->
<html>
  <head>
    <title>
      Upload and preview an image with Ajax
    </title>    
    <script language="JavaScript" type="text/javascript">
      
      var loadingHtml = "Loading..."; // this could be an animated image
      var imageLoadingHtml = "Image loading...";
    	var http = getXMLHTTPRequest();
      //----------------------------------------------------------------
    	function uploadImage() {
        var uploadedImageFrame = window.uploadedImage;
    	  uploadedImageFrame.document.body.innerHTML = loadingHtml;
    	  // VALIDATE FILE
        var imagePath = uploadedImageFrame.imagePath;
        if(imagePath == null){
          imageForm.oldImageToDelete.value = "";
        }
        else {
          imageForm.oldImageToDelete.value = imagePath;
        }
        imageForm.submit();
      }
      //----------------------------------------------------------------
      function showImageUploadStatus() {
        var uploadedImageFrame = window.uploadedImage;
        if(uploadedImageFrame.document.body.innerHTML == loadingHtml){
          divResult.innerHTML = imageLoadingHtml;
        }
        else {
          var imagePath = uploadedImageFrame.imagePath;
          if(imagePath == null){
            divResult.innerHTML = "No uploaded image in this form.";
          }
          else {
            divResult.innerHTML = "Loaded image: " + imagePath;
          }
        }
      }
      //----------------------------------------------------------------
      function getXMLHTTPRequest() {
      	try {
        	xmlHttpRequest = new XMLHttpRequest();
      	}
      	catch(error1) {
        	try {
          	xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
          }
          catch(error2) {
      	    try {
      		    xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      	    }
      	    catch(error3) {
      		    xmlHttpRequest = false;
      	    }
          }
        }
        return xmlHttpRequest;
      }
      //----------------------------------------------------------------
      function sendData() {
      	var url = "submitForm.php";
        var parameters = "imageDescription=" + dataForm.imageDescription.value;
        var imagePath = window.uploadedImage.imagePath;
        if(imagePath != null){
          parameters += "&uploadedImagePath=" + imagePath;
        }
        
      	http.open("POST", url, true);
    
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", parameters.length);
        http.setRequestHeader("Connection", "close");
    
      	http.onreadystatechange = useHttpResponse;
      	http.send(parameters);
      }
      //----------------------------------------------------------------
      function submitFormIfNotImageLoading(maxLoadingTime, checkingIntervalTime) {
        if(window.uploadedImage.document.body.innerHTML == loadingHtml) {
          if(maxLoadingTime <= 0) {
            divResult.innerHTML = "The image loading has timed up. "
                                + "Please, try again when the image is loaded.";
          }
          else {
            divResult.innerHTML = imageLoadingHtml;
            maxLoadingTime = maxLoadingTime - checkingIntervalTime;
            var recursiveCall = "submitFormIfNotImageLoading(" 
                              + maxLoadingTime + ", " + checkingIntervalTime + ")";
            setTimeout(recursiveCall, checkingIntervalTime);
          }
        }
        else {
          sendData();
        }
      }
    	//----------------------------------------------------------------
      function submitForm() {
        var maxLoadingTime = 3000; // milliseconds
        var checkingIntervalTime = 500; // milliseconds
        submitFormIfNotImageLoading(maxLoadingTime, checkingIntervalTime);
      }
      //----------------------------------------------------------------
      function useHttpResponse() {
      	if (http.readyState == 4) {
        	if (http.status == 200) {
          	divResult.innerHTML = http.responseText;
          	dataForm.reset();
          	imageForm.reset();
          	window.uploadedImage.document.body.innerHTML = "";
          	window.uploadedImage.imagePath = null;
        	}
      	}
      }

    </script>
  </head>
  <body>
    <h3>
      Form with preview of resized image with Ajax
    </h3>
    <form id="dataForm" name="dataForm">
      Image description: 
      <input name="imageDescription" id="imageDescription" type="text" 
            size="30"/>
    </form>
    
    <form id="imageForm" name="imageForm" enctype="multipart/form-data"
          action="uploadImage.php" method="POST" target="uploadedImage">
      <!-- Next field limits the maximum size of the selected file to 2MB.
           If exceded the size, an error will be sent with the file. -->
      <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
      Image: 
      <input name="imageToUpload" id="imageToUpload" type="file"
            onchange="uploadImage();" size="30"/>
      <br />
      Old uploaded image to delete (this field should be hidden):
      <br />
      <input name="oldImageToDelete" id="oldImageToDelete" type="text"
            size="50" />
    </form>
    
    <iframe id="uploadedImage" name="uploadedImage" src="" 
          style="width:200px; height:200px;"
          frameborder="0" marginheight="0" marginwidth="0"></iframe>
    
    <br /><br />
    
    <form>
    <input type="button" onclick="submitForm();" value="Submit" />
    </form>

    <br />
    
    <form>
    <input type="button" onclick="showImageUploadStatus();" value="Show image upload status" />
    </form>
    
    <div id="divResult"></div>

  </body>
</html> 
  #2 (permalink)  
Antiguo 24/05/2009, 15:47
 
Fecha de Ingreso: mayo-2009
Ubicación: Madrid, España
Mensajes: 9
Antigüedad: 14 años, 11 meses
Puntos: 11
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

uploadImage.php
Código PHP:
<?php
/*
Author: Alberto Moyano Sánchez
Date: 2009-05-24

Description:
- The script receives a file and a text with method="post".
- The file is validated to check that is a supported type of image, has no
  errors and is not larger than the maximum size allowed.
- If the dimensions of the image are larger than the maximum, it is resized.
- The image is uploaded to a temporary directory in the server.
- If the uploading was right, the script outputs an img html tag with the
  uploaded image, and a JavaScript variable with the temporary path of the
  uploaded image. If there was any error, the script outputs an error message. 
- If a text is sent a together with the file, it means that there was an
  image previously uploaded. This text is the path of the previously uploaded
  image, and it is removed before the new image is uploaded. 
*/
$pathToUpload "uploads_temp/";
$fileFieldName "imageToUpload";
// "image/pjpeg" is the type jpg for Internet Explorer
$allowedImageTypes = array("image/png""image/jpg""image/jpeg",
                           
"image/pjpeg""image/gif");
$maxImageSize 2000000// in bytes
//-----------------------------------------------------------------------------
function displayImage($imagePath) {
  
// BUG: the uppercase is very important. The extension of the image must
  //      be uppercase, if not, it is displayed distorted (Firefox 3.0.10)
  
echo "<img src='" strtoupper($imagePath) . "' />";
  echo 
"<script type = 'text/javascript'>";
  echo 
"var imagePath = '" $imagePath "';";
  echo 
"</script>";
  
// delay to test the uploading of the image
  //sleep(6);
}
//-----------------------------------------------------------------------------
// the functions imagecreateXXX raise a fatal error when trying
// to create an image larger than 3 MB
function createImageFactory($imagePath$imageType) {
  
$image null;
  if(
$imageType == "image/png") {
    
$image imagecreatefrompng($imagePath);
  }
  else if(
$imageType == "image/gif") {
    
$image imagecreatefromgif($imagePath);
  }
  else {
    
$image imagecreatefromjpeg($imagePath);
  }
  return 
$image;
}
//-----------------------------------------------------------------------------
function saveImage($image$imagePath$imageType) {
  
$resultSave false;
  if(
$imageType == "image/png") {
    
$resultSave imagepng($image$imagePath);
  }
  else if(
$imageType == "image/gif") {
    
// if the gif is animated, the function imagegif doesn't keep the
    // animation. The animation is lost in the process creating, resampling
    // and saving the image
    
$resultSave imagegif($image$imagePath);
  }
  else {
    
$resultSave imagejpeg($image$imagePath80);
  }
  return 
$resultSave;
}
//-----------------------------------------------------------------------------
function createNewImage($width$height$imageType) {
  
$image imagecreatetruecolor($width$height);
  
// set the transparency if the image is png or gif
  
if(($imageType == "image/png") || ($imageType == "image/gif")) {
    
imagealphablending($imagefalse);
    
imagesavealpha($imagetrue);
    
$transparent imagecolorallocatealpha($image255255255127);
    
imagefilledrectangle($image00$width$height$transparent);
  }
  return 
$image;
}
//-----------------------------------------------------------------------------
function uploadResizedImage($sourceImagePath$destinationImagePath$imageType) {
  
$resultSave false;
  list(
$width$height) = getimagesize($sourceImagePath);
  
$maximumDimension 200;
  if((
$maximumDimension >= $width) && ($maximumDimension >= $height)) {
    
// with the process of creating, resampling and saving the image, the
    // animation of an animated gif is lost. In order to keep the possible 
    // animation, if the image is smaller than the maximum size, it is
    // uploaded without any processing
    
$resultSave move_uploaded_file($sourceImagePath$destinationImagePath);
  }
  else {
    
// the function createImageFactory raises a fatal error when trying
    // to create an image larger than 3 MB
    
$sourceImage = @createImageFactory($sourceImagePath$imageType);
    if(
$width $height) {
      
$newWidth round($maximumDimension);
      
$newHeight round($height * ($newWidth $width));
    }
    else {
      
$newHeight round($maximumDimension);
      
$newWidth round($width * ($newHeight $height));
    }
    
$destinationImage createNewImage($newWidth$newHeight$imageType);
    
// the function imagecopyresampled is much better than the function
    // imagecopyresized, which distorts the image when resizing
    
$resultResize imagecopyresampled($destinationImage$sourceImage
                    
0000$newWidth$newHeight$width$height);
                    
    if(
$resultResize) {
      
$resultSave saveImage($destinationImage$destinationImagePath$imageType);
    }
  }
  
  return 
$resultSave;
}
//-----------------------------------------------------------------------------
// if there was an image uploaded before, remove it, because it is being
// substituted by another one
$oldImageToDelete $_POST["oldImageToDelete"];
if((
$oldImageToDelete != null) && (file_exists($oldImageToDelete))) {
  
unlink($oldImageToDelete);
}
// it must be checked first if there is an error with the file (e.g.
// larger than the maximum size allowed by the hidden field MAX_FILE_SIZE
// in HTML) than if type of the file is an allowed type, because if there 
// is an error, the type of the file may not be available
if ($_FILES[$fileFieldName]["error"] > 0) {
  echo 
"There is an error with the file.";
  echo 
"<br />";
  echo 
"Error code: " $_FILES["imageToUpload"]["error"];
}
else if(!
in_array($_FILES[$fileFieldName]["type"], $allowedImageTypes)) {
  echo 
"The type of the file is not a supported image type.";
  echo 
"<br />";
  echo 
"FILE: " $_FILES[$fileFieldName]["name"];
  echo 
"<br />";
  echo 
"File type: " $_FILES[$fileFieldName]["type"];
}
else if(
$_FILES[$fileFieldName]["size"] > $maxImageSize) {
// the function createImageFactory, called by uploadResizedImage raises 
// a fatal error when trying to create an image larger than 3 MB
  
echo "The uploaded file is larger than allowed.";
  echo 
"<br />";
  echo 
"Uploaded file size: " round($_FILES[$fileFieldName]["size"] / 1000) . " KB";
  echo 
"<br />";
  echo 
"Max allowed size: " round($maxImageSize 1000) . " KB";
}
else {
  
$imagePath $pathToUpload basename($_FILES[$fileFieldName]["name"]);
  if (
file_exists($imagePath)) {
    
unlink($imagePath);
  }
  if(
uploadResizedImage($_FILES[$fileFieldName]["tmp_name"], $imagePath$_FILES[$fileFieldName]["type"])) {
    
displayImage($imagePath);
  }
  else {
    echo 
"There was an error uploading the file" $imagePath ", please try again!";
    echo 
"<br />";
    echo 
"If the error continues, the uploaded file may not be accepted by the system.";
  }
}
?>
submitForm.php
Código PHP:
<?php
/*
Author: Alberto Moyano Sánchez
Date: 2009-05-24

Description:
- The script receives some data with method="post".
- One of this data may be a path of an image that was previously uploaded
  to a temporary directory in the server. If this datum exists, the script
  move the image from the temporary directory to a final one.
- The script process the rest of the data and produces some output. 
*/
$pathToMove "uploads/";

$imagePathParameterName "uploadedImagePath";
$imageDescriptionParameterName "imageDescription";

$imagePath $_POST[$imagePathParameterName];
$description $_POST[$imageDescriptionParameterName];

// the funtion file_exists doesn't find files whose name has special
// characters, like tildes
if (($imagePath != null) && (file_exists($imagePath))) {
  
$imagePathToMove $pathToMove basename($imagePath);
  if(
file_exists($imagePathToMove)) {
    
unlink($imagePathToMove);
  }
  if(
rename($imagePath$imagePathToMove)) {
    echo 
"The image " $imagePathToMove " was stored with the description '" $description "'.";
  }
  else {
    echo 
"There was an error moving the file " $imagePath " to " $imagePathToMove;
  }
}
else {
  echo 
"No image was uploaded for the description '" $description "'.";
}
?>
  #3 (permalink)  
Antiguo 24/05/2009, 15:49
 
Fecha de Ingreso: mayo-2009
Ubicación: Madrid, España
Mensajes: 9
Antigüedad: 14 años, 11 meses
Puntos: 11
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Aquí tenéis los comentarios completos de la cabecera del archivo html, con notas y explicaciones importantes.

Saludos.

Código HTML:
<!--
Author: Alberto Moyano Sánchez
Date: 2009-05-24

Description:
- This is a script to upload a form dynamically with Ajax, which contains an
  image and more data. The image is displayed in preview when it is selected.
- It consists of one html page and two php scripts. I wanted to do the
  funtionality of the first php script, which resizes the selected image,
  with Ajax instead of php. But it is not possible due to the limited action
  of JavaScript over the file field and the filesystem, because of security
  reasons. 
- There are actually two forms, one for the image and another for the rest
  of the data. (The reason is that JavaScript cannot take the selected file
  of the file field. It is explained some points below.) There is also an
  iframe which displays the image.
- The image form is automatically submited when a new file is selected. It is
  sent to a php script which resizes the image, stores it in a temporary 
  directory and displays it. The target of the image form is the iframe, so
  the image is displayed in it without need of reloading the whole page.
- The php script also writes in the iframe a control variable containing the
  temporary path of the uploaded image. This variable is key to dynamically
  upload the data form with Ajax.
- I wanted to do the resizing and previewing of the image with JavaScript,
  saving the submitting of the image form and the processing of the image
  at the server side. However it is not possible, because JavaScript cannot
  interact with the filesystem due to security reasons.
- Another handicap is that JavaScript can barely manage the file field, due
  to security reasons too. JavaScript can only read the name of the selected
  file but not the whole path. JavaScript can neither take the selected file
  to send it via Ajax. Thus, the file field cannot be sent via Ajax. The only
  way it can be sent is submitting the whole form. Therefore must be a
  separate form only for the file field, in order be able to submit only this 
  field and not the rest of the fields.
- The image form has another hidden field (for testing purpose it is visible)
  to store the name of the previous selected file, so it can be removed by
  the php script.
- The button to submit the data form takes the data fields and the control
  variable of the iframe, which says if there is an uploaded image and what
  its temporary path in the server is. A second php script is called, which
  moves the uploaded image from the temporary directory to the final one,
  and process the rest of the data.
  
Notes and improvements:
- This script has been tested with Firefox 3.0.10, Opera 9.64, Safari 4
  and Internet Explorer 6.0. Everything works fine (with the exception of
  the next point).
- The event "onchange" of the file field is well performed by all browsers
  when selecting a file with the button "browse". Firefox and Safari don't
  allow to write in the field, only to use the button to select a file.
  Explorer and Opera allow to write in the text box of the field. Explorer
  works fine and trhows the event "onchange" when the field loses the focus.
  Opera throws the event "onchange" everytime a key is pressed when typing
  in the field, what is not the desired behaviour.
- The file to upload must be validated with JavaScript previously to send
  it in the function uploadImage().
- If a file is sent, which is larger than the maximum size especified with
  the hidden field MAX_FILE_SIZE, PHP will throw an error, with error code
  2. To avoid such message and a futile sending, the file must be previously
  validated with JavaScript.
- In order to test the posible delays with the uploads, adjust the sleep
  statement in the function displayImage() in the file uploadImage.php.
  Adjust also the parameters in the JavaScript function submitForm().
- When an image is uploaded to the temporary directory to preview it, it is
  checked if there was a previously previewed image, to remove it from the
  temporary directory. However, the temporary directory must be emptied
  from time to time, because there will be files from the previewed images
  of forms that were finally not submited.
--> 
  #4 (permalink)  
Antiguo 09/08/2009, 12:06
Avatar de fhederico  
Fecha de Ingreso: agosto-2009
Mensajes: 247
Antigüedad: 14 años, 8 meses
Puntos: 23
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Mis felicitaciones, era justamente lo que buscaba solo me queda ajustarlo un poco mas.

Solo 1 correccion que he encontrado hasta el momento, si bien muestra una vista previa de las imagenes que vas a subir, se te olvido agregar las "image/x-png".

En el archivo "uploadImage.php", linea 22, deberia ir:

Código PHP:
$allowedImageTypes = array("image/png""image/x-png""image/jpg""image/jpeg",
                           
"image/pjpeg""image/gif"); 
Y en la linea 40, deberia ir:

Código PHP:
if(($imageType == "image/png") || ($imageType == "image/x-png")) { 
Bueno, eso fue lo que detecte, mis felicitaciones nuevamente.

Un Saludo

EDITO:

Aunque es algo obvio, pero lo agregare igual, es un mera nota, en la linea 19 es en donde se pone la carpeta en donde se crearan las imagenes "pequeñas" temporalmente, por llamarlas de algun modo.

Código PHP:
$pathToUpload "Imagenes_temporales/"
Solo sustituye el "Imagenes_temporales" por el nombre de tu carpeta, y esta carpeta debera estar dentro del mismo directorio en el cual esten los archivos.

Por ejemplo, si tengo los 3 archivos (uploadImage.php, submitForm.php, index.html), en la carpeta "prueba", deberas crear una carpeta dentro de "prueba" y luego sustituir "Imagenes_temporales" por el nombre que le pusiste a esa carpeta.

Última edición por fhederico; 09/08/2009 a las 13:46
  #5 (permalink)  
Antiguo 21/10/2009, 16:16
Avatar de JoseAlejandro_Realza  
Fecha de Ingreso: agosto-2008
Ubicación: Maracay - Venezuela
Mensajes: 192
Antigüedad: 15 años, 8 meses
Puntos: 2
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Esta Fenomenal hermano, yo estoy comenzando con Javascript para luego ir al Ajax y las consultas Asincronicas, y con este excelente ejemplo ya tendre buen material. Muchas Gracias.
__________________
Tu Guía Empresarial http://www.empresarial.org.ve Soluciones Empresariales

Atte: José Alejandro Realza
  #6 (permalink)  
Antiguo 23/05/2010, 11:44
 
Fecha de Ingreso: noviembre-2008
Mensajes: 110
Antigüedad: 15 años, 5 meses
Puntos: 2
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Hola el codigo funciona perfectamente.. solo dos cositas..

1- quiero colocar una imagen cargando.gif cuando este cargando la previsualizacion, me funciona abajo pero cuando lo subo al server no se ve la imagen.. ha de ser por el PHP, pork el k uso en mi compu es una vercion menor al del server..

2- quiero cambiar el nombre del archivo.. osea que me guarde el archivo con un nombre que le dare no el nombre original que trae el archivo..

ej: $nombre = time().".jpg";
  #7 (permalink)  
Antiguo 24/05/2010, 11:46
Avatar de cesarpunk  
Fecha de Ingreso: enero-2008
Ubicación: Lima
Mensajes: 943
Antigüedad: 16 años, 3 meses
Puntos: 9
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Muy bueno, me daré el tiempo para probarlo... pero sería perfecto si tuviera una precarga con porcentaje. Es que es inpredecible ver solo un gif animado o un mensajito de "espera", (que se puede conseguir con lenguaje de servidor y algo de js).

Espero puedas hacer esa mejora... sería estupendo.
__________________
Quitenme la vida pero no la bebida.
  #8 (permalink)  
Antiguo 15/06/2010, 05:22
 
Fecha de Ingreso: mayo-2009
Ubicación: Madrid, España
Mensajes: 9
Antigüedad: 14 años, 11 meses
Puntos: 11
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Hola a todos.

Gracias por vuestros comentarios :)

Por si a alguien le pueda interesar, decir que he hecho un plugin jQuery del UploaderPreviewer, que hará más sencillo implementar esta funcionalidad. Las características han mejorado. Éstas son algunas de ellas:

- Multi-navegador.
- Elimina las imágenes del directorio temporal que no se usan.
- Se puede configurar para pasar una lista de palabras clave para construir el nombre de las imágenes con ellas. Esta opción es interesante para SEO.
- Se muestra una imagen de cargando mientras se sube y previsualiza la imagen del usuario.
- Factoría de iframes para optimizar el consumo de memoria del navegador.
- Timeout si la imagen tarda mucho en cargar.
- Validaciones javascript y php.

Como aquí no se pueden adjuntar archivos, os dejo la dirección de otro foro donde sí pude ponerlo (no se puede poner un vínculo desde este foro hasta el otro). Es en inglés:

http://www.webdeveloper.com/forum/showpost.php?p=1090249&postcount=23

El zip contiene una pequeña demo del plugin. Es muy básico, pero para ver cómo funciona, sirve.

Si tenéis alguna pregunta, preguntadla, a lo mejor os puedo ayudar con ello.

Lo del tipo de imagen x-png ya está corregido, gracias :)

Respecto a lo de la barra de progresión para la carga de la imagen, decir que eso es difícil de hacer en internet, ya que influyen varios parámetros, algunos de ellos difíciles de medir y ajenos a nuestro control, como la congestión de la red o el propio proveedor de internet del usuario.

Sí se puede cuando se da un tiempo máximo de carga. Es una funcionalidad implementada en el plugin. En el archivo del plugin itemForm.js está definido este tiempo en la variable loadingTimeout, y el intervalo de progresión de la barra está determinado en la variable progressBarInterval.

Saludos.

Última edición por AMS777; 15/06/2010 a las 05:28
  #9 (permalink)  
Antiguo 15/06/2010, 19:00
Avatar de deirdre  
Fecha de Ingreso: mayo-2009
Mensajes: 690
Antigüedad: 14 años, 11 meses
Puntos: 45
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Gracias por tu trabajo, AMS777.

Lo bajo y lo probaré.

Saludos
  #10 (permalink)  
Antiguo 10/07/2010, 14:32
 
Fecha de Ingreso: noviembre-2009
Mensajes: 58
Antigüedad: 14 años, 5 meses
Puntos: 0
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Lo acabo de bajar y funciona perfecto
  #11 (permalink)  
Antiguo 29/10/2010, 10:44
Avatar de zeuzft  
Fecha de Ingreso: junio-2009
Ubicación: peru
Mensajes: 358
Antigüedad: 14 años, 10 meses
Puntos: 2
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

tengo un problema quiero que funcione en modalbox pero no me cargan los controles, que puedo hacer?
  #12 (permalink)  
Antiguo 19/07/2011, 13:48
 
Fecha de Ingreso: mayo-2011
Mensajes: 1
Antigüedad: 12 años, 11 meses
Puntos: 0
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Perdón por volver a abrir de nuevo este tema después de tanto tiempo, pero he puesto el código, y el problema es que se queda haciendo loading a la hora de cargar la imagen, y no se llega a cargar, creo que he seguido todo al pie de la letra.
  #13 (permalink)  
Antiguo 19/07/2011, 18:43
 
Fecha de Ingreso: julio-2010
Mensajes: 523
Antigüedad: 13 años, 9 meses
Puntos: 4
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

epale...wow de verdad funciona de miedo...pero tengo un problema...al momento de cuando selecciono el archivo...que se crea como una vista previa....resulta que esa vista previa aparece como una imagen dañada...que podra ser?...pero si se cargan y todo y se redimensionan funciona de a miedo eh jaja....digo es del plugin que unos comentarios mas arriba un usuario lo paso
  #14 (permalink)  
Antiguo 24/08/2011, 20:29
Avatar de emilianocepa  
Fecha de Ingreso: mayo-2007
Mensajes: 45
Antigüedad: 16 años, 10 meses
Puntos: 2
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Cita:
Iniciado por a_domin00 Ver Mensaje
Perdón por volver a abrir de nuevo este tema después de tanto tiempo, pero he puesto el código, y el problema es que se queda haciendo loading a la hora de cargar la imagen, y no se llega a cargar, creo que he seguido todo al pie de la letra.
a mi me sucede lo mismo, con firefox se me queda loading... poniendo tu ejemplo en mi pagina, pero tu ejemplo en firefox funciona correctamente; con chrome y IE funciona perfecto
el firebug me dice esto:
Cita:
imageForm is not defined
uploadImage() inicio.php (línea 25)
onclick() onclick (línea 2)
event = click clientX=689, clientY=244

imageForm.oldImageToDelete.value = "";
si nos puedes ayudar estaria agradecidisimoo, por cierto muy buen material

Última edición por emilianocepa; 25/08/2011 a las 14:59 Razón: agrege data
  #15 (permalink)  
Antiguo 27/08/2011, 12:19
Avatar de neglivv  
Fecha de Ingreso: julio-2011
Mensajes: 103
Antigüedad: 12 años, 9 meses
Puntos: 11
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Hola!!! muchas gracias por compartir esto, me calló como anillo al dedo ya que estoy haciendo una parte de un sistema que consiste en editar los perfiles de los usuarios y así ellos podrán pre-visualizar la imagen de perfil que seleccionan.
Tengo una dudita y le agradecería a cualquiera que me conteste: ¿este script se puede integrar en un formulario donde la persona pueda editar su nombre, correo e imagen?
Estoy usando jquery para validar los campos.
Gracias!
  #16 (permalink)  
Antiguo 27/08/2011, 12:46
Avatar de neglivv  
Fecha de Ingreso: julio-2011
Mensajes: 103
Antigüedad: 12 años, 9 meses
Puntos: 11
Sonrisa Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Cita:
Iniciado por emilianocepa Ver Mensaje
a mi me sucede lo mismo, con firefox se me queda loading... poniendo tu ejemplo en mi pagina, pero tu ejemplo en firefox funciona correctamente; con chrome y IE funciona perfecto
el firebug me dice esto:


si nos puedes ayudar estaria agradecidisimoo, por cierto muy buen material
Hola! a mi me paso eso porque el formulario donde coloque el input para subir el archivo no se llamaba "imageForm", asi que le cambie el nombre a eso y así si me funciono. Espero te sea de ayuda

Corrección: A mi me dio el mismo error en firefox después de integrar el script a mi sistema, yo lo solucione cambiando los elementos que sean de la forma imageForm.algo... por: document.getElementById('imageForm').algo.
Por ejemplo:
imageForm.reset(); a document.getElementById('imageForm').reset();

Última edición por neglivv; 28/08/2011 a las 13:14
  #17 (permalink)  
Antiguo 28/08/2011, 15:05
Avatar de emilianocepa  
Fecha de Ingreso: mayo-2007
Mensajes: 45
Antigüedad: 16 años, 10 meses
Puntos: 2
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

De primera¡¡¡¡ funciono perfecto, subo el codigo con los cambios para qeu funcione en mozilla:

Código:
 var loadingHtml = "Cargando..."; // this could be an animated image
      var imageLoadingHtml = "Imagen Cargada...";
    	var http = getXMLHTTPRequest();
      //----------------------------------------------------------------
    	function uploadImage() {
        var uploadedImageFrame = window.uploadedImage;
    	  uploadedImageFrame.document.body.innerHTML = loadingHtml;
    	  // VALIDATE FILE
        var imagePath = uploadedImageFrame.imagePath;
        if(imagePath != null){
          //imageForm.oldImageToDelete.value = imagePath;
		  document.getElementById('imageForm').oldImageToDelete.value = imagePath;
        }
        
      //imageForm.submit();
	   document.getElementById('imageForm').submit();
      }
      //----------------------------------------------------------------
      function showImageUploadStatus() {
        var uploadedImageFrame = window.uploadedImage;
        if(uploadedImageFrame.document.body.innerHTML == loadingHtml){
          divResult.innerHTML = imageLoadingHtml;
        }
        else {
          var imagePath = uploadedImageFrame.imagePath;
          if(imagePath == null){
            divResult.innerHTML = "No uploaded image in this form.";
          }
          else {
            divResult.innerHTML = "Loaded image: " + imagePath;
          }
        }
      }
      //----------------------------------------------------------------
      function getXMLHTTPRequest() {
      	try {
        	xmlHttpRequest = new XMLHttpRequest();
      	}
      	catch(error1) {
        	try {
          	xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
          }
          catch(error2) {
      	    try {
      		    xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      	    }
      	    catch(error3) {
      		    xmlHttpRequest = false;
      	    }
          }
        }
        return xmlHttpRequest;
      }
      //----------------------------------------------------------------
      function sendData() {
      	var url = "submitForm.php";
        var parameters = "imageDescription=" + dataForm.imageDescription.value;
        var imagePath = window.uploadedImage.imagePath;
        if(imagePath != null){
          parameters += "&uploadedImagePath=" + imagePath;
        }
        
      	http.open("POST", url, true);
    
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", parameters.length);
        http.setRequestHeader("Connection", "close");
    
      	http.onreadystatechange = useHttpResponse;
      	http.send(parameters);
      }
      //----------------------------------------------------------------
      function submitFormIfNotImageLoading(maxLoadingTime, checkingIntervalTime) {
        if(window.uploadedImage.document.body.innerHTML == loadingHtml) {
          if(maxLoadingTime <= 0) {
            divResult.innerHTML = "The image loading has timed up. "
                                + "Please, try again when the image is loaded.";
          }
          else {
            divResult.innerHTML = imageLoadingHtml;
            maxLoadingTime = maxLoadingTime - checkingIntervalTime;
            var recursiveCall = "submitFormIfNotImageLoading(" 
                              + maxLoadingTime + ", " + checkingIntervalTime + ")";
            setTimeout(recursiveCall, checkingIntervalTime);
          }
        }
        else {
          sendData();
        }
      }
    	//----------------------------------------------------------------
      function submitForm() {
        var maxLoadingTime = 3000; // milliseconds
        var checkingIntervalTime = 500; // milliseconds
        submitFormIfNotImageLoading(maxLoadingTime, checkingIntervalTime);
      }
      //----------------------------------------------------------------
      function useHttpResponse() {
      	if (http.readyState == 4) {
        	if (http.status == 200) {
          	divResult.innerHTML = http.responseText;
          	dataForm.reset();
          	//imageForm.reset();
			document.getElementById('imageForm').reset();
          	window.uploadedImage.document.body.innerHTML = "";
          	window.uploadedImage.imagePath = null;
        	}
      	}
      }
Una duda para que las imagenes me queden centradas en el iFrame como puedo solucionarlo.... Gracias
  #18 (permalink)  
Antiguo 25/09/2011, 05:15
 
Fecha de Ingreso: mayo-2009
Ubicación: Madrid, España
Mensajes: 9
Antigüedad: 14 años, 11 meses
Puntos: 11
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Hola.

Perdonad que no haya respondido a los últimos comentarios de este tema.

¿Seguís teniendo problemas o ya lo tenéis todo controlado?

neglivv, sí que se puede integrar esta funcionalidad con otros elementos de formularios, como casillas de texto. ¿Has visto cómo hacerlo?

El problema con Firefox no he terminado de verlo, porque este script está desarrollado precisamente con Firefox.

Un saludo.
  #19 (permalink)  
Antiguo 26/09/2011, 04:17
 
Fecha de Ingreso: mayo-2009
Ubicación: Madrid, España
Mensajes: 9
Antigüedad: 14 años, 11 meses
Puntos: 11
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Hola.

He puesto una demo del plugin aquí

http://dondedeportes.es/uploaderPreviewer

Espero que os sea de utilidad.

Si tenéis algún comentario, por favor, ponedlo en este foro.
  #20 (permalink)  
Antiguo 07/10/2011, 15:50
 
Fecha de Ingreso: agosto-2011
Mensajes: 3
Antigüedad: 12 años, 8 meses
Puntos: 0
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Hola muchas gracias por compartir tan buen material. Yo lo he probado tal cual esta en esta ultima liga publicada pero no me muestra las imagenes, en su lugar aparece en icono de la X en rojo, según yo lo estoy haciendo tal cual. ¿Alguién podria ayudarme diciendome en que estoy fallando? Muchas gracias.
  #21 (permalink)  
Antiguo 08/10/2011, 03:41
 
Fecha de Ingreso: mayo-2009
Ubicación: Madrid, España
Mensajes: 9
Antigüedad: 14 años, 11 meses
Puntos: 11
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Hola, lll1994.

Gracias por utilizar el plugin.

Por favor, utiliza la última versión. Te la puedes descargar de la página de demo:

http://dondedeportes.es/uploaderPreviewer/

También puedes llegar hasta ella desde la página oficinal de jQuery:

http://plugins.jquery.com/project/UploaderPreviewer

La versión que se descarga de ahí es la misma que está funcionando. Así que, si no te funciona correctamente, debe ser algo de la configuración. Revisa configuration.php, y comprueba que la url sea la correcta.

Un saludo.
  #22 (permalink)  
Antiguo 23/10/2011, 12:14
 
Fecha de Ingreso: octubre-2011
Mensajes: 1
Antigüedad: 12 años, 6 meses
Puntos: 1
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Saludos cordiales. Agradezco a quien se tome el tiempo de contestar mi inquitud.
Como puedo centrar la imagen en este caso. Yo lo edite a mi necesidad lo puse en tablas para poder ordenar la posicion de la foto pero ahora quiero centrarlo. archivos uploadimage.php y submitform.php no los modifique.

prueba.php
Código PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
Author: Alberto Moyano Sánchez
Date: 2009-05-24
Description: [...]
Notes and improvements: [...]
-->
<html>
  <head>
<?php
    sleep
(2);
    include_once(
"menu.php");
     
?>    
    <script language="JavaScript" type="text/javascript">
         //aqui va todo el scrip q se menciona mas arriba.
    </script>

  </head>
  <body>
  <div id="formularior" align="center">    
      <form name="nuevo_producto" action=""onSubmit="enviarProducto(); return false">
    <input  type="hidden" name="IdProducto" type="number" id="IdProducto" />

      <table border="0" width="60%">
  <tr>
    <td width="5%">Producto</td>
    <td width="10%">
        <select name="codigo1" >
                <option  value="P01" selected>Computadora</option>
                <option  value="P02">Notebook</option>
                <option  value="P03">Monitor</option>
                <option  value="P04">Scanner</option>
                <option  value="P05">Impresora</option>
        </select>
    </td>
    <td width="30%" rowspan="3"><iframe id="uploadedImage" name="uploadedImage" src="" style="width:200px; height:200px;" frameborder="0" marginheight="0" marginwidth="0"></iframe></td>
  </tr>

  <tr>
    <td width="5%">Marca</td>
    <td width="10%">
        <select name="codigo2" >
                <option  value="01" selected>Hp</option>
                <option  value="02">Dell</option>
                <option  value="03">Samsung</option>
                <option  value="04">Sonny</option>
                <option  value="05">LG</option>
                <option  value="06">Toshiba</option>
                <option  value="07">Lenovo</option>
                <option  value="08">Epson</option>
                <option  value="09">Cannon</option>
                <option  value="10">IBM</option>
                <option  value="11">Ensamblada</option>
        </select>
    </td>
  </tr>

  <tr>
    <td width="5%">Descripcion</td>
    <td width="10%">
        <textarea rows="5" cols="23" name="despro" cols="40%" rows="2" id="despro" placeholder="Ingrese Descripcion" required></textarea>
    </td>
  </tr>
  <tr>
    <td width="5%">Foto</td>
    <td width="10%">
        <form id="dataForm" name="dataForm"><input type=hidden name="imageDescription" id="imageDescription" type="text" size="30"/></form>
        <form [B]align="center"[/B] id="imageForm" name="imageForm" enctype="multipart/form-data" action="uploadImage.php" method="POST" target="uploadedImage">
      <!-- Next field limits the maximum size of the selected file to 2MB.If exceded the size, an error will be sent with the file. -->
      <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
      <input [B]align="center"[/B] name="imageToUpload" id="imageToUpload" type="file" onchange="uploadImage();" size="16"/><br />
      <!--Old uploaded image to delete (this field should be hidden):<br />-->
      <input type=hidden name="oldImageToDelete" id="oldImageToDelete" type="text" size="50" />
    </form>
    </td>
    <td width="60%"><form>
        <!--<input type="button" onclick="submitForm();" value="Submit" /></form><form><input type="button" onclick="showImageUploadStatus();" value="Ruta imagen" /></form>-->
        <input name="Submit" type="submit" onclick="submitForm(); value="Grabar" />
        <input type="button" onclick="showImageUploadStatus();" value="Ruta Imagen" />
    </td>
  </tr>
</table>
</form>
</div>
   <div id="divResult"></div>
  </body>
  </html>

si deseo grabar el scrip <script language="JavaScript" type="text/javascript"> en un archivo aparte, para llamarlo arriba de mi archivo prueba.php como lo grabo con q extension y como lo llamo? (para usarlo como si fuera una libreria o algo asi).
  #23 (permalink)  
Antiguo 21/06/2012, 00:18
 
Fecha de Ingreso: septiembre-2011
Mensajes: 17
Antigüedad: 12 años, 7 meses
Puntos: 0
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Hola, se que este post tiene su tiempo pero recién ahora lo veo y me parece muy bueno pero quisiera saber si es posible adjuntar la opción de subir imagenes junto a otros campos como nombre, dirección, ciudad, etc y que al presionar el botón enviar se guarden los campos en la base de datos y en un campo llamado fotos guarde el nombre de todas las imagenes, EJ.: foto1.jpg|foto2.jpg|foto3.jpg|foto4.jpg

Desde ya muchas gracias!
  #24 (permalink)  
Antiguo 22/06/2012, 12:55
 
Fecha de Ingreso: mayo-2009
Ubicación: Madrid, España
Mensajes: 9
Antigüedad: 14 años, 11 meses
Puntos: 11
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Cita:
Iniciado por negromelchor Ver Mensaje
Hola, se que este post tiene su tiempo pero recién ahora lo veo y me parece muy bueno pero quisiera saber si es posible adjuntar la opción de subir imagenes junto a otros campos como nombre, dirección, ciudad, etc y que al presionar el botón enviar se guarden los campos en la base de datos y en un campo llamado fotos guarde el nombre de todas las imagenes, EJ.: foto1.jpg|foto2.jpg|foto3.jpg|foto4.jpg

Desde ya muchas gracias!
Hola.

Échale un vistazo a la demo del plugin:

http://dondedeportes.es/uploader-previewer

Ahí podrás ver una demo con cuatro campos. Tres son imágenes, y el otro es un campo de texto. Al pulsar el botón "guardar" se guardan los cuatro campos, incluido el de texto, que es lo que vas buscando.

Espero que te resulte de ayuda.
  #25 (permalink)  
Antiguo 22/06/2012, 20:31
 
Fecha de Ingreso: septiembre-2011
Mensajes: 17
Antigüedad: 12 años, 7 meses
Puntos: 0
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Gracias AMS777, eso mismo estaba buscando, tengo otra consulta, que tendría que editar para que se pueda guardar el formulario de igual manera sin que se haya cargado ningúna foto? ya que en mi caso seria un campo opcional el de las fotos.

Gracias :D
  #26 (permalink)  
Antiguo 24/06/2012, 20:48
 
Fecha de Ingreso: septiembre-2011
Mensajes: 17
Antigüedad: 12 años, 7 meses
Puntos: 0
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

La verdad que está excelente pero no logro insertar los campos de texto en la base de datos, en que archivo iria el insert y como obtengo los valores? Si me podrias dar una ayudita te agradeceria enormemente.

Muchas gracias y saludos!!!
  #27 (permalink)  
Antiguo 25/06/2012, 00:25
 
Fecha de Ingreso: septiembre-2011
Mensajes: 17
Antigüedad: 12 años, 7 meses
Puntos: 0
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Bueno ya pude lograr guardar los datos en la BD, es que me faltaba completar el campo insertOrUpdateAjaxUrl en itemForm.js, ahora lo que me faltaria es ver como se hace para que se pueda enviar igual el formulario si el usuario no selecciona ningúna imagen.

Muchas gracias
  #28 (permalink)  
Antiguo 04/07/2012, 23:45
 
Fecha de Ingreso: septiembre-2011
Mensajes: 17
Antigüedad: 12 años, 7 meses
Puntos: 0
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Sigo avanzando y ya me falta lo último y es poder editar las imagenes, ya logro visualizarlas al momento de editar pero al llamar la función updateUpload() no tengo en claro como deben ir las imagenes que están en la base de datos.

Saludos y gracias!!!
  #29 (permalink)  
Antiguo 22/07/2012, 16:02
 
Fecha de Ingreso: septiembre-2011
Mensajes: 17
Antigüedad: 12 años, 7 meses
Puntos: 0
Respuesta: Subir, reducir y vista previa de una imagen con AJAX - Ejemplo completo

Hola AMS, encontré en un foro en Inglés una respuesta en la que explicas como editar/actualizar las imagenes ya subidas:

Check the Initialize forms to update files section in the documentation (http://dondedeportes.es/uploader-previewer). There you can see:

Code:

<div class="imageForms" images="image1.png,image2.jpg,image3.gif"></div>

You have to place the existing image names in the imageForms div, within the images attribute.

You have to read this attribute in javascript and populate the image forms, in the $(document).ready(), for instance. The attribute may be removed in order to clean the code:

Code:

if ($('div.imageForms[images]').length) {

var imageFilenames = $('div.imageForms[images]').attr('images').split(',');

$.uploaderPreviewer.populateImages(imageFilenames) ;

$('div.imageForms[images]').removeAttr('images');
}

The image names in the comma-separated string are splitted into an array, which is used by populateImages().

So far, if the plugin configuration is right, the images should be displayed on page load. And also if the configuration is right, you will be able to remove or replace anyone of them.

The working flow in the form is the same for insert and for update. The difference comes when the form is submitted. For an update, you will have to loop over every image and call the complex function updateUpload() of uploadedFile.php.

updateUpload() gets the name of the image comming from the form, the name of the stored image and a keyword list. If both names are equal, this means that the image remains as it was. Nothing is performed. The stored image name (which is equal to the image name from the form) is returned.

If the names are different, this means that the image was changed. Then, the old image is deleted and the new one moved from the temp directory, were it was, to the uploads directory. A new filename is generated with the keyword list. The new filename is then returned.

Me podrias dar un ejemplo del punto marcado en negrita? Es que no logro actualizar las imagenes, updateUpload no me devuelve nada.

Muchas gracias!!!
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 11 personas




La zona horaria es GMT -6. Ahora son las 21:00.